Dart报错:const列表字面量的值必须为常量,如何解决?
解决Flutter中Dart的const列表字面量报错问题
问题代码
const SizedBox( // 此处的const是报错根源 width: double.infinity, child: RawMaterialButton( fillColor: Color(900), elevation: 0.0, padding: EdgeInsets.symmetric(vertical: 20.0), shape: RoundedRectangleBorder(), )
报错信息
"message": "const列表字面量中的值必须为常量。\n尝试从列表字面量中移除'const'关键字。",
"source": "dart", const位于SIZED BOX开头
解决方法
- 直接移除SizedBox前的const关键字:代码里的
RawMaterialButton及其参数(比如Color(900)、RoundedRectangleBorder())并非编译时常量,不符合const构造Widget的要求,去掉const即可解决报错。修改后代码:
SizedBox( width: double.infinity, child: RawMaterialButton( fillColor: Color(900), elevation: 0.0, padding: EdgeInsets.symmetric(vertical: 20.0), shape: RoundedRectangleBorder(), )
- 可选优化(如需保留const):如果想通过const优化性能,需确保所有子组件和参数都是常量:
- 修正
Color写法:Color(900)格式错误,应使用ARGB常量值,比如const Color(0xFF000000)(黑色示例) - 给无参数构造器添加const:比如
const RoundedRectangleBorder()、const EdgeInsets.symmetric(vertical: 20.0)
修改后可正常使用const SizedBox:
- 修正
const SizedBox( width: double.infinity, child: RawMaterialButton( fillColor: const Color(0xFF000000), elevation: 0.0, padding: const EdgeInsets.symmetric(vertical: 20.0), shape: const RoundedRectangleBorder(), )
内容的提问来源于stack exchange,提问作者Ghulam Murtaza
相关产品推荐
相关产品推荐

