在颤振中更新冻结类中的深度嵌套数组

boo*_*boy 7 arrays immutability dart flutter

我在颤振中有一个冻结的课程,如下所示:

@freezed
abstract class Data with _$Data {
  const factory Data({
    String id,
    String name,
    String parentId,//null if it is the root element
    @Default([]) List<Data> children,
  }) = _Data;
}
Run Code Online (Sandbox Code Playgroud)

该类包含一个名为的属性children,它是同一类的列表,即Data.

当前允许的最大嵌套深度为 20 级。我面临的问题是如何children通过添加或删除项目来更新特定的深度嵌套列表。此外,此更新应保持不变并返回一个新的更新Data类。

我尝试copyWith()在冻结的类上使用方法,但在我的场景中嵌套很深时无法弄清楚。

Rém*_*let 2

您可以copyWith与展开运算符 (...) 结合来克隆列表。

假设你有:

abstract class Data with _$Data {
  const factory Data({
    String name,
    @Default([]) List<Data> children,
  }) = _Data;
}


var root = Data(
  name: 'root',
  children: [
    Data(name: 'first'),
  ],
)
Run Code Online (Sandbox Code Playgroud)

您可以克隆树并root通过执行以下操作添加一个子树:

root = root.copyWith(children: [
  ...root.children,
  Data(name: 'second'),
])
Run Code Online (Sandbox Code Playgroud)