flutter - 为什么当我在 dart 中使用具有 equatable 的类并且只是一个列表作为属性时,copyWith 方法返回相同的对象,相同的 hascode
问题描述
我正在使用 bloc 并且它按预期工作,但是今天我注意到当我使用 copyWith 发送相同的状态(RefreshState)时出现了一个意外行为,该状态在第二次调用后没有触发。然后我做了一个测试,创建了两个对象并进行了比较,但结果是它们是同一个对象,很奇怪。
那么为什么会这样呢?,这是我的课:
class Model extends Equatable {
final List<Product> mostBuyProducts;
const Model({
this.mostBuyProducts,
});
Model copyWith({
List<Product> mostBuyProducts,
}) =>
Model(
mostBuyProducts: mostBuyProducts ?? this.mostBuyProducts,
);
@override
List<Object> get props => [
mostBuyProducts,
];
}
然后我使用 CopyWith 方法,如(在集团内):
Stream<State> _onDeleteProduct(OnDeleteProduct event) async* {
state.model.mostBuyProducts.removeWhere((p) => p.id == event.id);
var newMostBuyProducts = List<Product>.from(state.model.mostBuyProducts);
final model1 = state.model;
final model2 = state.model.copyWith(mostBuyProducts: newMostBuyProducts);
final isEqual = (model1 == model2);
yield RefreshState(
state.model.copyWith(mostBuyProducts: newMostBuyProducts));
}
isEqual 返回真:/
顺便说一句,这是我的州级
@immutable
abstract class State extends Equatable {
final Model model;
State(this.model);
@override
List<Object> get props => [model];
}
解决方案
推荐阅读
- node.js - 使用get方法删除数据是正确的吗?
- deep-learning - 如何使用 Fasttext 构建 lemmatizer
- c++ - SearchPathW 冻结
- firebase - 如果存在颤动,Firestore 会增加 int 值
- python - 如何在 keras 中实现 maclaurin 系列?
- javascript - Django 在 html 模板中获取 modelformset_factory 输入字段 ID
- c++ - Mac VSCode 调试器总是显示关于 ';' 的错误 和 ':'
- python - 如何产生一个新的外壳?
- amazon-web-services - Packer 构建在最后一个命令上挂起
- swift - 在 switch 中正确制定 if 语句