Home > Enterprise >  Flutter - TextField content does not scroll automatically when inserting text
Flutter - TextField content does not scroll automatically when inserting text

Time:03-10

everyone! When I use the keyboard to input normally, the content will automatically scroll to the end when the content width exceeds the width of the TextField; but when I use TextEditingController to set the content for the TextField, when the content exceeds the width of the TextField, the content will not automatically scroll to the end.

code show as below

class _TextFieldPageState extends State<TextFieldPage> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField content not scroll'),
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              width: 100,
              child: TextField(
                controller: _controller,
                maxLines: 1,
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  // insert 'Flutter'
                  _controller.text  = 'Flutter';
                  // change cursor position to end
                  _controller.selection = TextSelection(
                    baseOffset: _controller.text.length,
                    extentOffset: _controller.text.length,
                  );
                },
                child: Text('insert text'))
          ],
        ),
      ),
    );
  }
}

keyboard input:

keyboard input

TextEditingController set text:

insert text use TextEditingController

How to make the content of TextField scroll to the end automatically when inserting text using Controller? thanks!!!

CodePudding user response:

This way worked for me. Change the function of your onPressed to this:

ElevatedButton(
              onPressed: () async {
                // insert 'Flutter'

                _editingController.text  = 'Flutter1';
                await Future.delayed(Duration(milliseconds: 10));
                _scrollController
                    .jumpTo(_scrollController.position.maxScrollExtent);
                print("Jumpted");
                _focusNode.unfocus();
                await Future.delayed(Duration(milliseconds: 10));
                _focusNode.requestFocus();
              },
              child: Text('insert text'),
            )

And the text field to this:

TextField(
                controller: _editingController,
                focusNode: _focusNode,
                scrollController: _scrollController,
                maxLines: 1,
              )

The main thing to know is that TextField has another controller called ScrollController enter image description here

  • Related