Flutter开发:虚拟键盘弹出时如何实现页面内容自动上移
问题根因
输入框被虚拟键盘遮挡存在两个核心问题:
- 自定义Dialog的内容高度写死为完整屏幕高度,没有预留键盘弹出后的空间,Scaffold默认的键盘适配逻辑被固定高度的SizedBox拦截,无法生效
- 静态Column不支持滚动,键盘弹出后底部的输入框被遮挡时也无法手动滑动查看
修复方案
步骤1:调整MyModal类的布局逻辑
修改后的MyModal代码如下:
class MyModal extends StatelessWidget { const MyModal({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; // 获取键盘弹出时的底部偏移 final bottomInset = MediaQuery.of(context).viewInsets.bottom; return Dialog( // 配置Dialog的内边距适配键盘 insetPadding: EdgeInsets.only(bottom: bottomInset), child: Scaffold( // 开启页面自动适配键盘的逻辑 resizeToAvoidBottomInset: true, body: SizedBox( // 高度改为屏幕高度减去顶部状态栏高度,不强制占满全屏 height: size.height - MediaQuery.of(context).viewInsets.top, width: size.width, // 用SingleChildScrollView包裹Column支持滚动 child: SingleChildScrollView( child: Column( children: const [ SizedBox( height: 400, ), TextField( obscureText: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ) ], ), ), ), ), ); } }
步骤2:可选优化
如果不需要Dialog占满全屏,可以去掉SizedBox的height固定配置,改为让内容自适应高度,适配效果会更灵活。
内容的提问来源于stack exchange,提问作者Millenial2020
相关产品推荐
相关产品推荐

