[英]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.