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

Flutter错误:常量构造函数参数必须为常量表达式

问题解决:Flutter中StatelessWidget传入参数在const组件中报错

错误原因

你给Center和Text组件加了const修饰符,但name是当前Widget的实例成员(哪怕是final修饰,也是运行时才确定的变量),而const组件要求所有子组件和参数必须是编译时常量,两者冲突导致报错。

修复方案

去掉Center或Text前面的const关键字即可——因为name是动态传入的,不能用const组件包裹。

修复后的代码:

class ContainerShowingDifferentAlgsets extends StatelessWidget {
  ContainerShowingDifferentAlgsets({required this.name});
  final String name;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 50.0,
      color: Colors.white24,
      child: Center(
        child: Text(
          name,
          // style可以保留const,因为是编译时常量
          style: const TextStyle(fontSize: 25.0, color: Colors.deepOrangeAccent),
        ),
      ),
    );
  }
}

补充说明

不要随意给组件加const,只有当所有子组件和参数都是固定常量时,才适合用const来优化性能。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:18:10