dart - 只有在构造函数飞镖中不为空时才更新最终字段
问题描述
我有一个名为 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 或空。
解决方案
您不能两次初始化一个字段。您config
使用初始化形式 ( this.config
) 和初始化列表条目进行初始化config = ...
。
我不确定您要做什么config
,但首先将其声明为普通参数,然后弄清楚您想要做什么:
AppState({AuthState auth, RConfig config})
: auth = auth ?? new AuthState(), config = config; // or something
推荐阅读
- amazon-web-services - 无法填充 AWS Glue ETL 作业指标
- python - 加密 python(.py) 文件
- python-3.x - Keras fit_generator 给出尺寸不匹配错误
- c# - 在 .NET Core 上的 Studio Code 中找不到 ICollectionView
- r - 用应用族替换生成图形的嵌套 for 循环
- cscore - 使用 cscore 库减小 WAV 文件大小
- python - 大量的python多处理导致内存错误
- java - 如果数据库查询在 Spring Boot webapp REST API 控制器中返回空对象,如何以未经授权的用户身份发送 401 和 404?
- javascript - 如何从 JSON 字符串化对象数组中读取数据并遍历它并使用相同的对象
- javascript - 解析对象数组以格式化数据