flutter - 如何为可选参数使用非常量值
问题描述
我正在尝试为我的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]
});
有没有办法在不将我的小部件转换为有状态的小部件的情况下解决这个问题?
提前谢谢你。
解决方案
您可以使用初始化列表来使用非常量值初始化最终实例字段:
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
指的是构造函数参数。如果没有值传递给构造函数,则使用??
运算符使用默认值。
您可以在此处了解有关初始化列表的更多信息。
您可以在此处了解有关??
操作员的更多信息。
推荐阅读
- ios - 从 Visual Studio Windows 发布 Xamarin IOS 应用程序的存档不起作用
- java - 将字符串拆分为对象列表
- ios - 如何在按钮点击时显示底部导航栏上方的视图
- android - 类 Matcher 不需要类型参数
- django - 如何更改 SelectField 上的查询集?
- c# - 如何使用 C# 中的 Generic 计算高于和低于平均值的分数?
- neo4j - 如何在 Neo4j 中获取所有数据或仅获取其大小?
- pandas - 熊猫数据框中行的分组总和和差异
- cakephp - 条件插件加载 Cakephp
- c# - 为什么在运行 .NET GitHub 操作工作流时出现“连接被拒绝”错误?