在颤动中,如何将
showModalBottomSheet
与 isDismissible:true
一起使用,并在用户点击模态栏时关闭键盘,或者如果未显示键盘关闭底部工作表?
默认情况下,两者都会弹出,我想处理一个然后处理另一个。
您需要检测键盘是否可见,然后您可以使用
PopScope
来控制ModalBottomSheet
的关闭动作
class SheetWidget extends StatefulWidget {
const SheetWidget({super.key});
@override
State<SheetWidget> createState() => _SheetWidgetState();
}
class _SheetWidgetState extends State<SheetWidget> with WidgetsBindingObserver{
var _isKeyboardVisible = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeMetrics() {
final bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
final newValue = bottomInset > 0.0;
if (newValue != _isKeyboardVisible) {
setState(() {
_isKeyboardVisible = newValue;
});
}
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: !_isKeyboardVisible,
child: Center(
child: TextField(
onTapOutside: (ev) {
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
);
}
}