繁体   English   中英

如何在不触发任何其他操作的情况下在 TextField 外部点击时隐藏键盘?

[英]Howto hide the keyboard in flutter when tapping outside of the TextField without triggering any other actions?

您好我有以下(简化的)代码:

class Example extends StatelessWidget {
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).focusedChild?.unfocus(),
      child: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                print("Button pressed!");
              },
              child: Text("Click me"),
            ),
            TextField(),
          ],
        ),
      ),
    );
  }
}

此代码生成以下 UI:

在此处输入图像描述

当我点击蓝色按钮时,“按下按钮”。 被打印并且键盘没有消失,这里的问题。 是这种行为不是我想要的。 我希望当我单击TextField之外的某处时键盘消失,并且即使我直接单击它也不会触发该按钮。 因此,例如,如果我单击按钮,则键盘应该消失而没有任何其他操作/副作用(在这种情况下不会打印任何内容)。 但是应该仍然可以正常地与TextField进行交互。

注意:禁用按钮不是一个好的选择,因为在我的真实案例场景中,页面是由很多复杂的小部件构建的,禁用它们非常复杂。

现在已经在那里停留了一段时间。 希望你能帮我:)

用手势检测器包裹脚手架,然后轻按聚焦焦点 scope

例子

 class Test extends StatelessWidget { const Test({Key? key}): super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: const Scaffold(), ); } }

将您的 Scaffold Widget 包裹在一个 Button 中,它可以是 Gesture Detector 或 Inkwell。 然后在其中添加 unfocus 方法。

GestureDetector(
  onTap: () => FocusScope.of(context).unfocus(),
  child: const Scaffold(
  body: TextFormField(
   decoration: OutlineInputBorder()),
);

我还需要在单击日期选择器(另一个小部件)时隐藏键盘

根据我的经验,当我点击某个不是小部件的地方时,GestureDetector 键盘会隐藏自己。 否则它不会隐藏自己。

只需将GestureDetector更改为Listener并添加

onPointerDown: (PointerDownEvent event) => FocusManager.instance.primaryFocus?.unfocus(),给了我解决方案。

所以,在你的例子中,你应该做的是,用一个Listener包裹按钮“点击我”并给它onPointerDown ,这应该在你按下按钮时隐藏你的键盘。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM