跨平台开发 / 系统课时

用 copyWith 更新模型

用 copyWith 更新模型

Freezed 模型通常按不可变对象使用:状态变化时不是改掉原对象,而是基于旧值创建新对象。copyWith 正是这条更新路径的核心,尤其适合只修改嵌套状态中的少数字段,以及把可空字段明确清成 null。

学习目标

  • 理解 copyWith 为什么比直接修改字段更适合不可变状态
  • 能更新一层字段和嵌套对象中的局部字段
  • 能区分“未传参数”和“显式传入 null”

为什么不直接修改字段

@freezed 生成的数据类通常作为不可变快照使用。创建对象后,业务代码不应把它当成可随处修改的容器。这样旧状态不会被后续逻辑悄悄污染,状态管理层也能通过新旧对象清晰地识别一次状态变化。

因此,需要改变状态时应调用 copyWith 创建新实例。没有传入的字段沿用旧值,传入的字段使用新值,原对象本身保持不变。

更新一层与嵌套字段

下面是完整示例。假设文件名为 profile.dart,项目已经配置 freezed_annotation、freezed 与 build_runner,并已完成代码生成。

dart
import 'package:freezed_annotation/freezed_annotation.dart';

part 'profile.freezed.dart';

@freezed
abstract class Profile with _$Profile {
  const factory Profile({
    required String name,
    String? nickname,
  }) = _Profile;
}

@freezed
abstract class UserState with _$UserState {
  const factory UserState({
    required Profile profile,
    required bool loading,
  }) = _UserState;
}

void main() {
  const state = UserState(
    profile: Profile(name: 'Alice', nickname: 'Neo'),
    loading: false,
  );

  final next = state.copyWith(
    profile: state.profile.copyWith(nickname: null),
    loading: true,
  );

  print('old nickname: ${state.profile.nickname}');
  print('new nickname: ${next.profile.nickname}');
  print('old loading: ${state.loading}');
  print('new loading: ${next.loading}');
}

预期输出:

text
old nickname: Neo
new nickname: null
old loading: false
new loading: true

这里发生了两层复制:外层 state.copyWith 创建新的 UserState,内层 state.profile.copyWith 创建新的 Profile。旧的 state 和 state.profile 都保持原值,因此可以继续用于比较、日志记录或状态回退。

可空字段为什么能显式改成 null

手写 copyWith 时常见一个歧义:如果可选参数本身以 null 表示“没有传值”,调用方就难以同时表达“保持旧值”和“把字段清空”。Freezed 生成的 copyWith 会在内部区分参数未提供与参数明确传入 null。

因此,state.profile.copyWith() 表示继续保留原昵称,而 state.profile.copyWith(nickname: null) 表示明确把昵称清空。表单重置、接口字段撤销和筛选条件清除等场景都依赖这一区别。

如何验证不可变更新

验证时不要只检查新对象,还应确认旧对象仍保存原值。核心检查点是目标字段已经变化、没有指定的字段继续保留,并且旧实例没有受到影响。

如果一次局部更新需要连续调用很多层 copyWith,通常说明状态结构已经过深。此时可以考虑把高频变化的子状态拆成独立模型,让更新边界更清楚。

按自己的节奏,确认真正理解。

目录与阅读设置

记录一个想法

用 copyWith 更新模型

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通