當點擊 TextFormField
時,會自動顯示 Soft Keyboard,但點擊其他地方,卻不會自動關閉 Soft Keyboard,必須自行關閉之。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功在離開
TextFormField
自動關閉 Soft Keyboard
TextFormField
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
class _Home extends State<Home> {
Widget build(BuildContext context) {
var appBar = AppBar(title: const Text('TextFormField Close Keyboard'));
var textFormField = TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
onTapOutside: (event) {
FocusScope.of(context).unfocus();
});
var body = Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
textFormField,
],
),
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 17
var textFormField = TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
onTapOutside: (event) {
FocusScope.of(context).unfocus();
});
onTapOutside()
:- 當
TextFormField
獲得焦點時,系統會自動顯示 Soft Keyboard 以供輸入。Flutter 使用FocusNode
來追蹤 Widget 是否獲得了焦點 FocusScope.of(context)
獲取當前頁面的FocusScope
,這是管理焦點狀態的對象。當你呼叫unfocus()
時,它會移除目前的焦點,類似於將焦點取消
- 當 TextFormField 沒有獲得焦點時,系統會認為沒有需要輸入的地方,因此自動關閉 Soft Keyboard
- 當
Conclusion
- 當點擊 TextFormField 以外區域,會自動關閉 Soft Keyboard