Flutter Column嵌套Row时Container报非const构造函数错误如何解决?
问题原因
你代码中Row组件的children数组前显式加了const修饰符,该修饰符会强制要求数组内的所有子元素都必须是可常量实例化的组件,而Flutter默认Container构造函数没有const实现,因此触发了类型校验报错,和外层Column是否添加const修饰无关。
解决方法
有两种可行的修改方案:
方案1(最简便):移除Row children的const修饰
直接把Row的children参数前的const关键字删掉即可,修改后的代码片段如下:
Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, // 删掉此处的const children: <Widget>[ Padding( padding: EdgeInsets.all(8.0), child: Text("ሓደ መኣዲ"), ), Container( child: Padding( padding: EdgeInsets.all(8.0), child: Icon(Icons.favorite_border, color: Colors.red,), ), ), ], )
方案2(保留const性能优化):调整组件结构适配const要求
你当前代码里的Container没有设置任何除child外的属性,属于冗余组件,可以直接删除,同时给剩余可const的组件加const修饰,既保留常量优化还能减少组件层级:
Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const <Widget>[ Padding( padding: EdgeInsets.all(8.0), child: Text("ሓደ መኣዲ"), ), // 删掉冗余的Container,直接用const修饰Padding和Icon Padding( padding: EdgeInsets.all(8.0), child: Icon(Icons.favorite_border, color: Colors.red,), ), ], )
内容的提问来源于stack exchange,提问作者Awet
相关产品推荐
相关产品推荐

