Implement text editing feature with custom keyboard in Flutter

Viewed 1500

I have implemented the custom keyboard (with the help of Table->card->button widgets) which looks like below, If the user press the button then I capture the text and just display it in to the screen.

enter image description here

By using this, user can enter the data but they cannot edit it. How can I implement the text editing feature in this case ?

I have tried to use the TextField widget to fit in my case, it gives all the features including text editing. But it does not allow to use the custom keyboard.

1 Answers

You could use the readOnly and showCursor properties of the TextField like this:

TextField(
  controller: _textController,
  readOnly: true,
  showCursor: true,
),

And then you could replace the selected text or insert a new text, like this:

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