2

How do I insert letters in between a TextField's text in flutter?

Example

Text in the text field: I run faster than him.

Expected Result

I want to move the curser before the run and type can .

TextField(
    controller: _controller,
    onChanged: (value) {
        // Do something when the text changes
    },
    decoration: InputDecoration(
        labelText: 'Enter your text',
    ),
),
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Rosh
  • 29
  • 4
  • can you make your question more clear? I can't understand it. but I think you should use formatters to do what you want. If you make it more clear, I'll create a formatted in an answer – Mahdi Dahouei Jul 04 '23 at 07:45

1 Answers1

2

This is my example code, might be helpful

class _MyAppState extends State<MyApp> {
  final _controller = TextEditingController();
  final _focus = FocusNode();

  @override
  void initState() {
    super.initState();
    _controller.text = "I run faster than him.";
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            TextField(
              controller: _controller,
              focusNode: _focus,
            ),
            ElevatedButton(
              child: Text("change text field value"),
              onPressed: () {
                FocusScope.of(context).requestFocus(_focus);
                /// insert text
                _controller.text = "I can run faster than him.";
                /// change cursor position
                _controller.selection = TextSelection.fromPosition(TextPosition(offset: 5));
              },
            )
          ],
        ),
      ),
    );
  }
}
Zhentao
  • 344
  • 7