首页 > 解决方案 > 为什么当我在 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];
}

标签: flutterdartblocflutter-bloc

解决方案


推荐阅读