【问题标题】:How do I dismiss the keyboard in TextFormfeild flutter 2.0.1如何在 TextFormfeild Flutter 2.0.1 中关闭键盘
【发布时间】:2021-06-09 00:43:17
【问题描述】:

嘿,我如何在这里关闭键盘?我希望在该区域外点击时关闭键盘。

  Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
  child: TextFormField(
    keyboardType: TextInputType.number,
    maxLength: 10,
    controller: widget._phoneController,
    onTap: () => FocusScope.of(context).unfocus(),
    inputFormatters: [
      //input type
      FilteringTextInputFormatter.allow(
        RegExp(r'[0-9]'),
      ),
    ],
    //how the text box is decorated
    decoration: buildInputDecoration(
        Icons.phone, 'Enter your 10 digit phone number'),
  ),
);
}

【问题讨论】:

标签: flutter flutter2.0


【解决方案1】:

您可以使用可以检测点击的小部件来包装跨越整个屏幕的父小部件。在onClick

FocusScope.of(context).unfocus()

FocusScope.of(context) 获取当前焦点节点,.unfocus() 取消焦点。

这是有效的,因为当点击 TextFormField 时,它会消耗点击。所以父小部件的onClick 不会被触发。所以不会发生散焦。

当我们在外部点击时,父窗口小部件会消费点击事件,因为它的子窗口不会消费它。这样就触发了父级的onClick

下面是一个例子。你可以看到demo on DartPad
(不过,最好在移动设备上运行它,这样你就可以看到屏幕键盘。)

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hide keyboard in TextFormField when touched outside'),
      ),
      body: GestureDetector(
        onTap: () {
          print('Clicked outside');
          FocusScope.of(context).unfocus();
        },
        child: Container(
          color: Colors.white,
          child: Form(
            child: Column(
              children: [
                TextFormField(
                  onTap: () => print('Clicked TextFormField'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    为我工作:)

      TextField(
            onSubmitted: (value) async {
              FocusScope.of(context).unfocus();
            },
        })
    

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多