如何修复Flutter中使用Expanded和Flexible仍出现render flex溢出报错
Flutter RenderFlex overflowed报错解决方案
你的代码存在两个核心问题导致溢出报错:
ListView.builder的item外层使用Flexible属于无效用法:Flexible仅能在Row、Column、Flex这类Flex布局容器中生效,ListView的item容器不属于Flex布局,因此你加的这个Flexible完全没有作用。- 评论项布局宽度未做限制:每个评论项的
Row中,右侧承载用户名、评论内容、操作按钮的Column外层没有用Expanded包裹,Row布局时不会自动限制右侧内容的宽度,当评论文本过长时就会超出屏幕横向宽度,触发溢出报错。
修复步骤
- 移除
ListView.builder的itemBuilder返回值外层无用的Flexible组件 - 给Row中包裹右侧评论内容的
Padding组件套一层Expanded,强制限制右侧内容的最大宽度为Row除去左侧头像后的剩余屏幕宽度 - 可按需给评论文本组件增加
maxLines和overflow属性,控制长文本的展示逻辑
修复后的核心代码片段
Expanded( child: ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: 10, itemBuilder: (BuildContext context, int index) { // 删掉了外层无用的Flexible return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(30, 0, 0, 0), child: Column( children: [ CircleAvatar( radius: 16.0, backgroundImage: NetworkImage( '_loadedPhotos[index]["thumbnailUrl"],'), backgroundColor: Colors.red, ), ], ), ), // 右侧Padding外层加Expanded限制宽度 Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(20, 0, 30, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'User Name', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.black, fontSize: 16, ), ), SizedBox( height: 7, ), Text( '3 hour ago', style: TextStyle( color: Colors.grey, fontSize: 12, ), ), SizedBox( height: 14, ), Text( 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. dolor sit amet, consectetur adipiscing elit.', // 按需开启下面三个属性控制长文本展示 // maxLines: 3, // overflow: TextOverflow.ellipsis, // softWrap: true, style: TextStyle( color: Colors.grey, fontSize: 14, ), ), SizedBox( height: 10, ), Divider( thickness: 1, color: Colors.grey, ), Row( children: [ IconButton( icon: Icon(isliked ? Icons.favorite_border : Icons.favorite), onPressed: () { setState(() { isliked = !isliked; }); }, ), Text( 'Like', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.black, fontSize: 14, ), ), SizedBox( width: 25, ), IconButton( onPressed: () {}, icon: Icon( FontAwesomeIcons.comment, size: 20, )), Text( 'Comments', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.black, fontSize: 14, ), ), ], ), SizedBox( height: 10, ), ], ), ), ) ], ); }, ), )
修改完成后即可解决横向溢出的问题。
内容的提问来源于stack exchange,提问作者Abdulrhman Waleed
相关产品推荐
相关产品推荐

