如何在 TextField 之外的任何地方点击使其失去焦点?

Jus*_*808 10 flutter

当我点击 aTextField它获得焦点。键盘打开,打字工作正常。现在我已经打完字了,我在除了 之外的任何地方点击TextField,我希望焦点会改变并且键盘会消失,但事实并非如此。

如何在TextField使其松散焦点之外的任何地方进行敲击?

小智 13

您可以使用onTapOutside的参数TextField

TextField(
    onTapOutside: (event) {
        FocusManager.instance.primaryFocus?.unfocus();
    }
),
Run Code Online (Sandbox Code Playgroud)


Ali*_*sam 7

您可以将整个屏幕包裹起来,GestureDetector这样当您触摸 上的任意位置时GestureDetectoronTap就会调用隐藏软键盘的方法。

new Scaffold(
  body: new GestureDetector(
    onTap: () {
      /*This method here will hide the soft keyboard.*/
      FocusScope.of(context).requestFocus(new FocusNode());
    },
    child: new Container(
       //More work here
    )
 )
Run Code Online (Sandbox Code Playgroud)