Flutter:将键盘聚焦在后退导航上

Flutter: Focus keyboard on back navigation

我想在用户使用导航栏中的后退按钮导航回来后聚焦一个 textField。你是怎样做的?我尝试了 TextField 小部件的 autofocus 属性。但这仅在首次创建小部件时向前导航时有效。 iOS上有viewDidAppear方法,Flutter有类似的吗?

谢谢!

您需要提供 TextField FocusNode,然后您可以 await 用户返回并设置 FocusScope.of(context).requestFocus(myNode) 导航发生时。

简单演示:

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