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

Flutter自定义Widget中Color属性阴影设置及默认值报错问题

问题解答

首先,Colors.red.shade900的数据类型就是Color,和你定义的backgroundColor属性类型完全匹配,出错的原因并非类型不兼容,而是你使用了const构造函数,而Colors.red.shade900不属于编译时常量,无法作为const构造的默认参数。

你可以通过以下两种方式解决:

  • 移除构造函数的const关键字,就能正常使用Colors.red.shade900作为默认值:
class ChartHeader extends StatelessWidget {
  final String title;
  final Color backgroundColor;
  ChartHeader({
    Key? key,
    required this.title,
    this.backgroundColor = Colors.red.shade900,
  }) : super(key: key);
  // 其他Widget代码
}
  • 若想保留const构造,可将默认值替换为对应的编译时常量形式,比如Colors.red.shade900对应的十六进制颜色值Color(0xFFB71C1C):
class ChartHeader extends StatelessWidget {
  final String title;
  final Color backgroundColor;
  const ChartHeader({
    Key? key,
    required this.title,
    this.backgroundColor = const Color(0xFFB71C1C),
  }) : super(key: key);
  // 其他Widget代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:00:54