Flutter 点击空白处取消TextField焦点并收起键盘
在Flutter中,要实现点击空白处取消TextField
的焦点并收起键盘,可以使用GestureDetector
包裹TextField
,并在onTap
回调中调用FocusScope.of(context).requestFocus(FocusNode());
来取消焦点。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyTextField(),
),
),
);
}
}
class MyTextField extends StatefulWidget {
@override
_MyTextFieldState createState() => _MyTextFieldState();
}
class _MyTextFieldState extends State<MyTextField> {
FocusNode focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
focusNode.unfocus();
FocusScope.of(context).requestFocus(FocusNode());
},
child: TextField(
focusNode: focusNode,
),
);
}
}
在这个例子中,我们创建了一个MyTextField
状态ful widget,它包含一个TextField
和一个GestureDetector
。当在GestureDetector
上点击时,它会取消焦点并请求一个新的FocusNode
,这会导致键盘被收起。
评论已关闭