首页 > 解决方案 > 如何为可选参数使用非常量值

问题描述

我正在尝试为我的FlutButton小部件创建一个自定义类,当我尝试使用方括号指定颜色属性时,我收到此错误:

The default value of an optional parameter must be constant.
class CustomFlatButton extends StatelessWidget {
  final String text;
  final Color color;
  final Color textColor;
  CustomFlatButton({
    this.text='Default sign in text', 
    this.color = Colors.white70, 
    this.textColor = Colors.grey[900] // this is what is causing the error [900]
  });

有没有办法在不将我的小部件转换为有状态的小部件的情况下解决这个问题?

提前谢谢你。

标签: flutterdart

解决方案


您可以使用初始化列表来使用非常量值初始化最终实例字段:

class CustomFlatButton extends StatelessWidget {
  CustomFlatButton({
    this.text='Default sign in text', 
    this.color = Colors.white70, 
    Color textColor,
  }) : textColor = textColor ?? Colors.grey[900];
  
  final String text;
  final Color color;
  final Color textColor;
}

在这种情况下,textColor = textColor ?? Colors.grey[900]赋值的左手对应,this.textColor右手textColor指的是构造函数参数。如果没有值传递给构造函数,则使用??运算符使用默认值。


您可以在此处了解有关初始化列表的更多信息
您可以在此处了解有关??操作员的更多信息。


推荐阅读