3

我正在尝试在 bloc 类中实现复选框逻辑。为此,我List<bool> checked在 bloc 类代码中创建如下。当CheckBoxClicked事件触发时,第一次状态更新,我可以看到选中的框。

class CartProductsListBloc
    extends Bloc<CartProductsListEvent, CartProductsListState> {
  CartProductsListBloc() : super(InitialCartProductsListState());

  final ProductRepository productRepository = ProductRepository();
  List<bool> checked = List<bool>();
  var productsList;

  @override
  Stream<CartProductsListState> mapEventToState(
      CartProductsListEvent event) async* {
    if (event is FetchCartProductsList) {
      yield FetchingInProgress();
      try {
        productsList = await productRepository.loadListOfProductInUserCart();
        //initialize checked according to productsList
        for (int i = 0; i < productsList.length; i++) {
          checked.add(false);
        }
        yield FetchCartProductsListSuccess(
            productsList: productsList, checked: checked);
      } catch (error) {
        yield FetchCartProductsListFail(
            error: 'Fail to laod data. Please try again\nOr Report the issue');
      }
    }
    if (event is CheckBoxClicked) {
      checked[event.index] = !checked[event.index];
      yield CheckedBoxClickedHappened(
          productsList: productsList, checked: checked);
    }
  }
}

但在那之后,无论多少次CheckBoxClicked调用状态 UI 的事件都不会更新。当我热刷新时,会出现更改,这意味着逻辑工作正常,但问题是 Equatable 无法检测到列表/数组索引的更改。以下是CheckedBoxClickedHappened状态代码。

class CheckedBoxClickedHappened extends CartProductsListState {
  final productsList;
  final checked;
  const CheckedBoxClickedHappened({@required this.productsList, @required this.checked});

  @override
  List<Object> get props => [productsList, checked];
}

注意:我通过添加int count = 0;in bloc 类解决了这个问题,并且每次CheckBoxClicked触发事件时我都会更新 count++,如下所示

if (event is CheckBoxClicked) {
          checked[event.index] = !checked[event.index];
          yield CheckedBoxClickedHappened(
              productsList: productsList, checked: checked, count: count++);
        }

并处于状态

@override
      List<Object> get props => [productsList, checked, count];

问题的目的是要知道,Equatable 是否无法检测到 List 索引的变化或者我做错了什么?如果有任何疑问,请询问我会改进它。

4

0 回答 0