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
相关产品推荐
相关产品推荐

