仅当构造函数 dart 中不为空时才更新最终字段

Update final fields only if not null in constructor dart

我有一个名为 class 的 App,其中包含一些字段。 我只想在传递给构造函数的参数不为空时初始化最终字段。

例如,在下面的代码中,我只想在配置参数不为空时设置它。

我试过下面的代码,但它不起作用

@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 很陌生,但我知道我不能初始化 final 字段两次,但是有一些应用程序状态导致再次创建 AppState 并且 RConfig 当时可能为 null。

我的问题很简单,就是如何在分配它们之前检查多个最终字段的有效性,例如 null 或 empty。

您不能对一个字段进行两次初始化。您使用初始化形式 (this.config) 和初始化列表条目 config = ....

初始化 config

我不确定你想用 config 做什么,但首先将它声明为一个普通参数,然后再弄清楚你想做什么:

AppState({AuthState auth, RConfig config})
    : auth = auth ?? new AuthState(), config = config; // or something