【问题标题】:How to hide input keyboard on flutter after clicking phone back button in Textfield in Flutter?在 Flutter 的 Textfield 中单击电话后退按钮后,如何在 Flutter 上隐藏输入键盘?
【发布时间】:2020-10-05 12:42:27
【问题描述】:

我想在编辑 TextField 时点击手机后退按钮时隐藏键盘。但是当我尝试这个键盘快速关闭并重新打开后。我该如何解决这个问题?我在 Nexus 6 和 Pixel 2 上尝试了这个。

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('page', style: (TextStyle(fontSize: 25))),
      ),
      body: Center(
        child: TextField(
          autofocus: false,
          keyboardType: TextInputType.text,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: '--',
          ),
        ),
      ),
    );
  }

编辑:enter image description here

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我们需要代码。但我认为您的 TextField 的 autofocus 属性设置为 true。您需要将其更改为 false。

    编辑后: 您需要使用 WillPopScope。

    @override
    Widget build(BuildContext context) {
      return WillPopScope(
        onWillPop: _onBackPressed(context),
        child: Scaffold(
          appBar: AppBar(
            title: Text('page', style: (TextStyle(fontSize: 25))),
          ),
          body: Center(
            child: TextField(
              autofocus: false,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: '--',
              ),
            ),
          ),
        );
    }
    
    Future _onBackPressed(BuildContext context) {
     FocusScope.of(context).unfocus();
    }
    

    【讨论】:

    • 我添加了建议。
    • 它不适合我。我想在 TextField 中使用设备后退按钮(在键盘下方)关闭键盘。我想用后退按钮从文本字段中移除焦点。
    • 我看到了这篇文章,但它不适用于设备后退按钮,它仅用于单击文本字段外部并失去焦点它有用但并非每次都有用,可能用户会尝试设备的后退按钮以失去焦点。
    【解决方案2】:
      @override
      Widget build(BuildContext context) {
       return WillPopScope(
             child: Scaffold(.....),
              onWillPop: () async {
                var currentFocus = FocusScope.of(context);
                if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                  currentFocus.focusedChild.unfocus();
                  return false;
                }else{
                  return true;
                }
              },
            );
        }
    

    使用 WillPopScope 在按下事件时关闭键盘

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2021-10-06
      • 1970-01-01
      • 2012-04-30
      • 2012-11-15
      • 2021-03-23
      • 2022-01-22
      相关资源
      最近更新 更多