Flutter PieChart出现RenderBox未布局错误,求解决方案
Flutter PieChart 布局错误(RenderBox was not laid out)
首次在此提问,不会编程但需要开发应用,目前无力付费委托他人开发。反复遇到同一错误却不清楚原因及解决办法,原本期望正常显示饼图,但VSCode给出如下错误,触发组件为PieChart:
RenderBox 未完成布局:RenderPositionedBox#4dc8d relayoutBoundary=up5 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
package:flutter/…/rendering/box.dart:1
断言失败:第2001行第12位:'hasSize'
以下是我的代码:
Column( children: [ Padding( padding: const EdgeInsetsDirectional.only(top: 16), child: Container( decoration: BoxDecoration( color: const Color.fromARGB(255, 1, 0, 0), borderRadius: BorderRadius.circular(6)), width: 300, height: 200, child: Column( children:[ const Text( 'Votre Patrimoine', style: TextStyle(color: Colors.white), ), Row( children: [ Column( children: [ LayoutBuilder( builder: (context, constraints) { return const PieChart( dataMap: { '1': 25, '2': 75, }, colorList: [ Colors.blue, Colors.red, ], ); }, ) ], ) ] ), Column( children: [ const Text('Les 24 dernières heures', style: TextStyle(color: Colors.white),), Text(dayvariations, style: const TextStyle(color: Colors.white)) ] ) ],) ) ), ]
问题原因
这个错误核心是PieChart未获取到明确的尺寸约束。Flutter布局系统要求组件必须有确定的宽高才能完成渲染,你的代码里PieChart嵌套在多层Column、Row中,外层容器没给它分配固定尺寸,LayoutBuilder的约束也未被利用,导致PieChart无法确定自身大小,触发布局断言失败。
解决办法
1. 给PieChart设置固定尺寸
在PieChart外层包裹Container或SizedBox,指定明确宽高:
LayoutBuilder( builder: (context, constraints) { return Container( width: 100, height: 100, child: const PieChart( dataMap: { '1': 25, '2': 75, }, colorList: [ Colors.blue, Colors.red, ], ), ); }, )
2. 利用LayoutBuilder约束自适应尺寸
若想让PieChart根据父容器可用空间自适应,用SizedBox绑定LayoutBuilder的约束:
LayoutBuilder( builder: (context, constraints) { return SizedBox( width: constraints.maxWidth, height: constraints.maxHeight, child: const PieChart( dataMap: { '1': 25, '2': 75, }, colorList: [ Colors.blue, Colors.red, ], ), ); }, )
3. 给Row中的PieChart容器添加Expanded
外层Row需要给包含PieChart的Column分配空间,修改Row部分代码:
Row( children: [ Expanded( child: Column( children: [ LayoutBuilder( builder: (context, constraints) { return Container( width: 100, height: 100, child: const PieChart( dataMap: { '1': 25, '2': 75, }, colorList: [ Colors.blue, Colors.red, ], ), ); }, ) ], ), ), Column( children: [ const Text('Les 24 dernières heures', style: TextStyle(color: Colors.white),), Text(dayvariations, style: const TextStyle(color: Colors.white)) ] ) ] ),
内容的提问来源于stack exchange,提问作者Eymerick Thibaut
相关产品推荐
相关产品推荐

