我有一个名为App的类,其中包含一些字段。我只想在传递给构造函数的参数不为空的情况下初始化final字段。
例如,在下面的代码中,我只想在不为空的情况下设置config param。
我尝试了下面的代码,但它不起作用
@immutable
class App {
final AuthState auth;
final RConfig config;
App({AuthState auth, this.config}):
auth = auth ?? new AuthState(), config = config != null ? config : this.config ;虽然我是dart的新手,但我知道我不能初始化两次最终字段,但由于应用程序的状态,AppState会被再次创建,并且RConfig可能会在那时为空。
我的问题很简单,那就是如何在赋值前检查多个final字段的有效性,例如null或empty。
发布于 2018-07-27 05:34:11
一个字段不能初始化两次。您可以使用初始化形式(this.config)和初始化器列表条目config = ...来初始化config。
我不知道你想用config做什么,但首先将它声明为一个普通参数,然后弄清楚你想要做什么:
AppState({AuthState auth, RConfig config})
: auth = auth ?? new AuthState(), config = config; // or somethinghttps://stackoverflow.com/questions/51545494
复制相似问题