Flutter调试时出现RenderBox was not laid out错误求解决方案
问题根因
你遇到的hasSize断言失败是Flutter布局阶段的典型错误,本质是组件无法确定自身尺寸,具体触发原因有两个:
- transaction.dart高度约束冲突:你给金额展示的Container设置了
height: double.infinity,但它的父组件是Row,Row在纵轴方向默认不会给子组件传递固定高度约束,导致这个Container无法计算自身高度,最终触发布局失败。 - 交易列表无滚动容器约束:main.dart里装载所有Transaction组件的Column直接放在外层Column中,没有用可滚动组件包裹,后续交易条目增多超出屏幕高度时也会触发同类布局错误。
修复方案
第一步:修改transaction.dart的金额Container高度
不要使用height: double.infinity,用IntrinsicHeight包裹整个Row,让Row的高度自动适配最高的子组件即可,修改后代码如下:
@override Widget build(BuildContext context) { return Container( margin: EdgeInsets.all(4), width: double.infinity, child: Card( elevation: 8, shadowColor: Colors.indigo.shade200.withOpacity(0.6), color: Colors.grey.shade100, // 让Row高度自动适配子组件最高高度 child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 64, // 删掉double.infinity,高度跟随父Row自适应 alignment: Alignment.center, margin: EdgeInsets.all(8), padding: EdgeInsets.symmetric(vertical: 12), decoration: BoxDecoration( border: Border.all(color: Colors.indigo.shade900, width: 1), borderRadius: BorderRadius.all(Radius.circular(4))), child: CustomText(item.amount.toString(), EdgeInsets.all(4), Colors.indigo.shade900, 16, FontWeight.normal)), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomText( item.title.toString(), EdgeInsets.fromLTRB(4, 8, 4, 4), Colors.indigo.shade400, 16, FontWeight.bold), CustomText( dateFormat.format(item.date), EdgeInsets.fromLTRB(4, 8, 4, 4), Colors.indigo.shade500, 16, FontWeight.w400), ], ) ], ), ), ), ); }
第二步:给main.dart的交易列表加可滚动容器
把装载交易列表的Container包裹在Expanded和ListView里,既可以适配剩余屏幕高度,也能支持滚动避免条目溢出,修改后代码如下:
body: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: double.infinity, height: 128, child: Card( color: Colors.indigo.shade300, child: CustomText("Chart", EdgeInsets.all(8), Colors.white, 24, FontWeight.bold), elevation: 8, )), // 占满Column剩余高度 Expanded( child: Container( margin: EdgeInsets.fromLTRB(0, 8, 0, 0), // 用ListView替代Column支持滚动 child: ListView( shrinkWrap: true, children: transactionItems.map((item) { return Transaction(item); }).toList()), ), ) ], )
修改完成后重新运行即可解决Debug模式下的布局报错问题。
内容的提问来源于stack exchange,提问作者ch3x
相关产品推荐
相关产品推荐

