据我所知,Dart 不支持字素集群,尽管有人说支持它:
在它实施之前,我有哪些用于迭代字素集群的选项?例如,如果我有这样的字符串:
String family = '\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}'; //
String myString = 'Let me introduce my $family to you.';
并且在五个代码点系列表情符号之后有一个光标:
如何将光标向左移动一个用户感知的字符?
(在这种特殊情况下,我知道字素簇的大小,所以我可以做到,但我真正要问的是找到任意长的字素簇的长度。)
更新
我从这篇文章中看到 Swift 使用了系统的ICU库。在 Flutter 中可能会出现类似的情况。
补充代码
对于那些想玩我上面的例子的人,这里有一个演示项目。按钮将光标向右或向左移动。目前需要按 8 次按钮才能将光标移过家庭表情符号。
主要.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Grapheme cluster testing')),
body: BodyWidget(),
),
);
}
}
class BodyWidget extends StatefulWidget {
@override
_BodyWidgetState createState() => _BodyWidgetState();
}
class _BodyWidgetState extends State<BodyWidget> {
TextEditingController controller = TextEditingController(
text: 'Let me introduce my \u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} to you.'
);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(
controller: controller,
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text('<<'),
onPressed: () {
_moveCursorLeft();
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text('>>'),
onPressed: () {
_moveCursorRight();
},
),
),
],
)
],
);
}
void _moveCursorLeft() {
int currentCursorPosition = controller.selection.start;
if (currentCursorPosition == 0)
return;
int newPosition = currentCursorPosition - 1;
controller.selection = TextSelection(baseOffset: newPosition, extentOffset: newPosition);
}
void _moveCursorRight() {
int currentCursorPosition = controller.selection.end;
if (currentCursorPosition == controller.text.length)
return;
int newPosition = currentCursorPosition + 1;
controller.selection = TextSelection(baseOffset: newPosition, extentOffset: newPosition);
}
}