首页 > 解决方案 > 只有在构造函数飞镖中不为空时才更新最终字段

问题描述

我有一个名为 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 很陌生,但我知道我不能两次初始化最终字段,但是由于 AppState 会再次创建应用程序状态,并且当时 RConfig 可能为空。

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

标签: dartdart-pub

解决方案


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

我不确定您要做什么config,但首先将其声明为普通参数,然后弄清楚您想要做什么:

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

推荐阅读