【问题标题】:How do I use non-constant values for optional parameters如何为可选参数使用非常量值
【发布时间】:2020-11-10 03:14:51
【问题描述】:

我正在尝试为我的 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]
  });

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

提前,谢谢。

【问题讨论】:

标签: flutter dart


【解决方案1】:

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

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 指的是构造函数参数。如果没有向构造函数传递任何值,则使用 ?? 运算符使用默认值。


您可以learn more about the initializer list here.
你也可以learn more about the ?? operator here。

【讨论】:

  • 非常有帮助,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 2014-03-26
  • 2019-05-19
  • 1970-01-01
  • 2020-09-09
  • 2012-02-23
  • 1970-01-01
相关资源
最近更新 更多