【问题标题】:Implement text editing feature with custom keyboard in Flutter在 Flutter 中使用自定义键盘实现文本编辑功能
【发布时间】:2019-10-16 05:49:49
【问题描述】:

我已经实现了自定义键盘(在 Table->card->button 小部件的帮助下),如下所示,如果用户按下按钮,我会捕获文本并将其显示在屏幕上。

通过使用它,用户可以输入数据但不能编辑它。 在这种情况下如何实现文本编辑功能?

我尝试使用 TextField 小部件来适应我的情况,它提供了包括文本编辑在内的所有功能。但它不允许使用自定义键盘。

【问题讨论】:

  • 这个问题你解决了吗?
  • 是的,它适用于插入文本。但现在我也在尝试删除文本。
  • 如果您尝试删除选定的文本,那么您可以使用带有空字符串的 _insertText(),如果您想在按下删除按钮时删除最后一个字符,您可以执行类似 _textController 的操作。文本 = _textController.text.substring(0, _textController.text.length-2)。如果提供的答案解决了您的问题,请将其标记为已接受。谢谢!

标签: flutter flutter-layout mobile-application


【解决方案1】:

您可以像这样使用TextFieldreadOnlyshowCursor 属性:

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"]),
      ],
    ),
  );
}

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 2023-03-30
    • 2022-01-04
    • 2012-10-02
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多