2

I want to focus a textField after the user navigated back with the back button in the navigation bar. How do you do that? I tried the autofocus property of the TextField widget. But this only works when navigating forward when the widget gets created for the first time. On iOS there is the viewDidAppear method, is there something similar in Flutter?

Thanks!

Renato Stauffer
  • 340
  • 2
  • 7
  • 27

1 Answers1

3

You will need to provide your TextField a FocusNode, and then you can await the user to go back and set FocusScope.of(context).requestFocus(myNode) when the navigation happens.

Simple demonstration:

enter image description here

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => new _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  FocusNode n = new FocusNode();
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title:new Text("First Page")),
      body: new Center(
        child: new Column(
          children: <Widget>[
            new TextField(
              focusNode: n,
            ),
            new RaisedButton(onPressed: ()async{

              bool focus = await Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new SecondPage()));
              if (focus == true|| focus==null){

                  FocusScope.of(context).requestFocus(n);

              }
              },
            child: new Text("NAVIGATE"),),
          ],
        ),
      ),
    );
  }
}


class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(title:new Text("Second Page")),
    body: new Center(
      child: new RaisedButton(onPressed: (){Navigator.pop(context,true);},child: new Text("BACK"),),
    ),
    );
  }
}
Shady Aziza
  • 34,951
  • 15
  • 97
  • 103
  • It is good to note that the value of `focus` is `null` when the back button is pressed (as shown in the gif). It is `true` when the 'BACK' `RaisedButton` is pressed. – harm Oct 11 '18 at 07:36