我已经实现了如下所示的自定义键盘(借助Table-> card-> button小部件,如果用户按下按钮,则我捕获了文本并将其显示在屏幕上。
通过使用此选项,用户可以输入数据,但不能编辑。在这种情况下,如何实现文本编辑功能?
我已尝试使用TextField小部件来适应我的情况,它提供了包括文本编辑在内的所有功能。但是它不允许使用自定义键盘。
您可以像这样使用readOnly
的showCursor
和TextField
属性:
TextField(
controller: _textController,
readOnly: true,
showCursor: true,
),
然后您可以替换所选文本或插入新文本,如下所示:
@override
void initState() {
super.initState();
_textController = TextEditingController();
}
_insertText(String textToInsert) {
if (_textController.selection.start >= 0) {
int newPosition = _textController.selection.start + textToInsert.length;
_textController.text = _textController.text.replaceRange(
_textController.selection.start,
_textController.selection.end,
textToInsert,
);
_textController.selection = TextSelection(
baseOffset: newPosition,
extentOffset: newPosition,
);
} else {
_textController.text += textToInsert;
}
}
Widget _buildRow(List<String> texts) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: texts
.map((text) => RaisedButton(
child: Text(text), onPressed: () => _insertText(text)))
.toList());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Calc")),
body: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(16.0),
child: TextField(
controller: _textController,
readOnly: true,
showCursor: true,
),
),
_buildRow(["1", "2", "3"]),
_buildRow(["4", "5", "6"]),
_buildRow(["7", "8", "9"]),
],
),
);
}