dartuinavigationbarflutterviewdidappear

Flutter: Focus keyboard on back navigation


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!


Solution

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