Dart中如何实现可动态指定属性的通用类实例更新方法?
Dart 属于静态强类型语言,默认禁用反射能力,无法在运行时将字符串参数直接映射为类的属性名或copyWith的命名参数,因此你写的伪代码无法正常运行。有两种常用的实现方案可以满足你的需求:
方案1:枚举标识属性(类型安全,适合单属性更新场景)
先定义枚举来标识Entry类的所有可更新属性,通用方法内通过分支判断调用对应copyWith参数:
// 第一步:定义Entry属性枚举 enum EntryProperty { title, notes } // 第二步:实现通用更新方法 void updateUnsubmittedEntry(EntryProperty property, dynamic value) { switch (property) { case EntryProperty.title: _unsubmittedNewEntry = _unsubmittedNewEntry.copyWith(title: value as String); break; case EntryProperty.notes: _unsubmittedNewEntry = _unsubmittedNewEntry.copyWith(notes: value as String?); break; } notifyListeners(); } // 调用示例 updateUnsubmittedEntry(EntryProperty.title, "新标题"); updateUnsubmittedEntry(EntryProperty.notes, "新备注");
优点:调用逻辑简单,编译期校验属性名不存在拼写错误的可能。
方案2:函数式更新(更灵活,支持批量更新)
直接将更新逻辑作为入参传入,无需维护枚举和分支判断,同时支持单次修改多个属性:
// 实现通用更新方法 void updateUnsubmittedEntry(Entry Function(Entry original) updater) { _unsubmittedNewEntry = updater(_unsubmittedNewEntry); notifyListeners(); } // 调用示例:单属性更新 updateUnsubmittedEntry((entry) => entry.copyWith(title: "新标题")); // 调用示例:多属性同时更新 updateUnsubmittedEntry((entry) => entry.copyWith(title: "新标题", notes: "新备注"));
优点:不需要额外维护枚举和分支代码,扩展性极强,新增类属性时不需要修改通用更新方法的代码。
内容的提问来源于stack exchange,提问作者Corey Stewart
相关产品推荐
相关产品推荐

