Home > Back-end >  Flutter: give focus to just added TextField
Flutter: give focus to just added TextField

Time:12-07

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.

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

CodePudding user response:

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();
        },
  • Related