BottomSheet内嵌Navigator后全屏显示,求内容自适应高度解决方案
问题原因
Navigator组件默认会占据父级提供的全部可用空间,再加上你开启了isScrollControlled: true,showModalBottomSheet会给子组件分配全屏的可用空间,最终导致BottomSheet被拉伸至全屏。
解决方案
通过Wrap组件包裹Navigator,让Wrap根据内部内容的实际高度自动调整自身尺寸,从而让BottomSheet恢复自适应高度的行为。如果需要限制BottomSheet的最大高度,可以搭配ConstrainedBox一起使用。
修改后的完整代码
await showModalBottomSheet<void>( isDismissible: true, useSafeArea: true, isScrollControlled: true, backgroundColor: Colors.transparent, context: blocContext, builder: (BuildContext context) { // 使用Wrap包裹Navigator,限制其高度为内容实际高度 return Wrap( children: [ Navigator( onGenerateRoute: (context) => MaterialPageRoute<ModalRoute>( fullscreenDialog: false, builder: (context) => Container( color: Colors.white, child: Stack( fit: StackFit.loose, children: [ CustomScrollView( shrinkWrap: true, slivers: [ SliverToBoxAdapter( child: Container( height: 50, width: 50, color: Colors.yellow, ), ), SliverList.separated( itemCount: 5, itemBuilder: (context, index) { return Container( height: 30, color: Colors.green, ); }, separatorBuilder: (context, index) { return gapH20; }, ), ], ) ], ), ), ), ), ], ); }, );
可选优化:限制最大高度
如果希望BottomSheet不会超过屏幕的一定比例(比如70%),可以用ConstrainedBox包裹Wrap:
return ConstrainedBox( constraints: BoxConstraints( maxHeight: MediaQuery.of(context).size.height * 0.7, ), child: Wrap( children: [ // Navigator代码不变 ], ), );
内容的提问来源于stack exchange,提问作者Salvatore Ambrosio
相关产品推荐
相关产品推荐

