You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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优化性能,需确保所有子组件和参数都是常量:
    1. 修正Color写法:Color(900)格式错误,应使用ARGB常量值,比如const Color(0xFF000000)(黑色示例)
    2. 给无参数构造器添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:45:21