Flutter中AlertDialog遇键盘弹出上移问题的解决方法
解决AlertDialog在键盘弹出时上移的问题
可行方案一:用MediaQuery.removeViewInsets包裹对话框
直接在AlertDialog外层嵌套MediaQuery.removeViewInsets,同时开启maintainBottomViewPadding: true,就能屏蔽键盘弹出带来的视图内边距变化,让对话框固定在原位:
void _showAddBoxDialog() { TextEditingController nameController = TextEditingController(); showDialog( context: context, builder: (BuildContext context) => Dialog( backgroundColor: Colors.transparent, child: MediaQuery.removeViewInsets( context: context, maintainBottomViewPadding: true, child: AlertDialog( backgroundColor: const Color(0xFFF9F9F9), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), content: TextField( controller: nameController, autofocus: true, textInputAction: TextInputAction.done, decoration: const InputDecoration(hintText: 'Enter box name'), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('Cancel'), ), TextButton( onPressed: () { if (nameController.text.isNotEmpty) { // Save action here Navigator.pop(context); } }, child: const Text('Add'), ), ], ), ), ), ); }
可行方案二:将对话框嵌套在内部Scaffold中
把AlertDialog放进一个独立的Scaffold里,设置resizeToAvoidBottomInset: false,这个属性会阻止Scaffold为键盘调整布局,从而固定对话框位置:
void _showAddBoxDialog() { TextEditingController nameController = TextEditingController(); showDialog( context: context, builder: (BuildContext context) => Scaffold( backgroundColor: Colors.transparent, resizeToAvoidBottomInset: false, body: AlertDialog( backgroundColor: const Color(0xFFF9F9F9), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), content: TextField( controller: nameController, autofocus: true, textInputAction: TextInputAction.done, decoration: const InputDecoration(hintText: 'Enter box name'), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('Cancel'), ), TextButton( onPressed: () { if (nameController.text.isNotEmpty) { // Save action here Navigator.pop(context); } }, child: const Text('Add'), ), ], ), ), ); }
补充说明
之前设置外层Scaffold的resizeToAvoidBottomInset: false没用,是因为showDialog创建的对话框属于独立的Overlay层级,不受外层Scaffold的属性影响。上面两种方案都是直接在对话框自身层级内处理键盘布局调整,因此能解决问题。
内容的提问来源于stack exchange,提问作者Bob E
相关产品推荐
相关产品推荐

