Flutter唤起键盘时底部溢出、SingleChildScrollView包裹Column组件消失求解
解决方案
1. 修复SingleChildScrollView包裹Column后组件消失问题
核心原因是SingleChildScrollView会为子组件提供无限纵向高度,而Expanded需要依赖父组件的有限高度约束才能正常计算填充空间,二者冲突导致布局失效。
你可以通过LayoutBuilder获取父组件的可用高度,再通过ConstrainedBox给Column设置最小高度约束,即可保留原有Expanded的填充效果同时支持滚动,修改后的build代码如下:
@override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { return SingleChildScrollView( child: ConstrainedBox( // 给Column设置最小高度等于父组件可用高度 constraints: BoxConstraints(minHeight: constraints.maxHeight), child: Column( crossAxisAlignment: CrossAxisAlignment.start, // 适配高度,内容不足时占满父高度,内容超过时自动延伸 mainAxisSize: MainAxisSize.min, children: [ _buildWidget1(), _buildWidget2(), _buildWidget3(), // 原有的Expanded可以正常生效,承担分隔作用 Expanded(child: Container()), // 其他组件 ], ), ), ); }, ); }
2. 修复Bottom Sheet唤起键盘底部溢出问题
你当前已经开启了isScrollControlled: true并添加了键盘边距适配,溢出是因为Bottom Sheet的内容没有滚动能力,当键盘弹出后可用高度小于内容高度时就会触发错误。
给Bottom Sheet的内容套上SingleChildScrollView,同时可增加最大高度约束避免内容过长顶到状态栏,修改后的弹框代码如下:
void _bottomSheetButtonPressed(context) { showModalBottomSheet( barrierColor: Colors.transparent, backgroundColor: Colors.transparent, context: context, isScrollControlled: true, builder: (context) { return Padding( padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( // 限制Bottom Sheet最大高度为屏幕高度的90%,可按需调整 constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9), decoration: BoxDecoration( color: Colors.transparent, borderRadius: const BorderRadius.only( topLeft: Radius.circular(24), topRight: Radius.circular(24), ), ), // 内容套滚动组件,高度不足时自动滚动避免溢出 child: SingleChildScrollView( child: _showBottomSheetItemsWidget(), ), ), ); }, ); }
内容的提问来源于stack exchange,提问作者Luke Irvin
相关产品推荐
相关产品推荐

