【问题标题】:Flutter: Focus keyboard on back navigationFlutter:将键盘聚焦在返回导航上
【发布时间】:2017-12-25 03:23:03
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: dart uinavigationbar flutter viewdidappear


    【解决方案1】:

    您需要提供您的TextFieldFocusNode,然后您可以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"),),
        ),
        );
      }
    }
    

    【讨论】:

    • 请注意,当按下返回按钮时,focus 的值是null(如图 gif 所示)。按下“返回”RaisedButton 时为true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2022-06-11
    • 2021-08-26
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多