Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter: give focus to just added TextField

I need to give a focus on just created TextField.

The example code is here: https://dartpad.dev/?id=1c84c70d956efde95fa12820c9afa4aa

class _TestPageState extends State<TestPage> {
  List<TextEditingController> controllers = [
    TextEditingController(text: 'field 0')
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView.builder(
            itemCount: controllers.length,
            itemBuilder: (context, index) => TextField(
                controller: controllers[index],
                autofocus: index == controllers.length - 1)),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          setState(() {
            controllers.add(
                TextEditingController(text: 'field ${controllers.length}'));
          });
        },
      ),
    );
  }
}

In the dartpad it works fine, but doesn’t on a real device.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions why it doesn’t work on device and how to achieve that?
Thanks.

>Solution :

In that case, you can also create List<FocusNode> _focusNodes = [];, (add one FocusNode based on list).

Then add and request focus on last focus node.

 onPressed: () {
          setState(() {
            controllers.add(
                TextEditingController(text: 'field ${controllers.length}'));
            _focusNodes.add(FocusNode());
          });
          _focusNodes.last.requestFocus();
        },
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading