我们正在开发一种在Flutter中可以进行广泛写入和存储的软件。而且它还将支持撤消和重做功能。
目前,我们在不可变数据结构方面的经验为零。
在 flutter 的研究过程中,我想到了冻结软件包,用于不可变数据模型的代码生成器,这促使我理解了不可变数据集。但是使用不可变数据模型会带来各种挑战,例如-
最佳答案
Updating of deeply nested children of the data model
由于您使用的是Freezed,这应该不是问题。
Freezed提供了一种内置机制来更新深层嵌套的变量
https://github.com/rrousselGit/freezed#deep-copy
例如,假设您具有:
@freezed
abstract class Company with _$Company {
factory Company({String name, Director director}) = _Company;
}
@freezed
abstract class Director with _$Director {
factory Director({String name, Assistant assistant}) = _Director;
}
@freezed
abstract class Assistant with _$Assistant {
factory Assistant({String name, int age}) = _Assistant;
}
然后,而不是:
Company company;
Company newCompany = company.copyWith(
director: company.director.copyWith(
assistant: company.director.assistant.copyWith(
name: 'John Smith',
),
),
);
你可以写:
Company company;
Company newCompany = company.copyWith.director.assistant(name: 'John Smith');
Deep copying of whole data even on a minor change in any of the nested data model(Like a letter change in the google doc), would make our application slow.
使用不变性时,很少有理由制作“深拷贝”。
相反,它是执行的浅拷贝。
要继续
Company
示例,请假定您具有:var company = Company(
name: 'Google',
director: Director(
name: 'John',
),
)
然后,当您想更改公司名称时,只需要做:
company = company.copyWith(name: 'Facebook');
这样做时,不会重新创建
Director
。仅Company
是有效的。因为
Director
是不可变的,所以很好。我们无法更改Director
上的任何内容,因此即使两个对象使用相同的Director
也没有冲突的风险。We were planning to keep multiple copy of the the same model for supporting the undo or redo, but this will take a lot of memory space of the end user.
从上一点继续,您将存储的不是深拷贝,而是浅拷贝。
因此最终,对内存的影响减少了很多。
就像您提到的undo-redo一样,即使您没有使用不可变数据,也有可能仍然使用该内存。
关于flutter - 不可变或可变数据模型,应该用于设计Google表单,Google Doc等软件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61946954/