Flutter如何让承载ExpansionTile的Container实现动态高度消除空白
解决方案
你只需调整3处配置即可实现动态高度适配,同时兼顾多图场景的滚动需求:
- 移除外层Container的固定
height属性,改为添加最大高度限制,避免图片过多时区域过长 - 给内部ListView添加
shrinkWrap: true配置,让ListView自适应自身内容高度,而非强制撑满父容器 - 给内部ListView添加
physics: NeverScrollableScrollPhysics()配置,禁用内部滚动,和外层页面的SingleChildScrollView做联动,避免滚动冲突
修改后的代码片段如下:
_imageList.length != 0 ? Container( // 移除固定height,添加最大高度约束 constraints: BoxConstraints( maxHeight: MediaQuery.of(context).size.height * 0.5, ), width: MediaQuery.of(context).size.width * 0.8, child: ListView( // 新增适配内容高度配置 shrinkWrap: true, // 禁用内部滚动避免和外层页面滚动冲突 physics: const NeverScrollableScrollPhysics(), children: [ ExpansionTile( title: Text('Pictures'), onExpansionChanged: (value) { setState(() {}); }, children: List<Widget>.generate( _imageList.length, (index) => ListTile( // 注:原代码此处存在笔误,判断长度误用了第0张图的路径,已修正为index title: Text(_imageList[index] .path .split('/') .last .length > 25 ? _imageList[index] .path .split('/') .last .substring(0, 25) + '...' : _imageList[index].path.split('/').last), trailing: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ IconButton( icon: Icon( Icons.delete_outline, size: 20.0, color: Colors.red, ), onPressed: () { setState(() { _selected!.removeAt(index); _imageList.removeAt(index); }); }, ), ], ), ), ), ), ], ), ) : const SizedBox.shrink(),
修改后当图片数量少、ExpansionTile展开的总高度小于0.5倍屏幕高度时,Container会自动贴合内容高度,不会出现多余空白;当图片数量较多、总高度超过0.5倍最大限制时,才会触发内部ListView的滚动,不会撑破布局。
内容的提问来源于stack exchange,提问作者user16754196
相关产品推荐
相关产品推荐

