简体   繁体   中英

Flutter - Bloc only emits state when the state is not extending Equatable

I recently started using bloc and im stuck here.

I have a state:

class BasketState extends Equatable{
  final Map<Item, int> itemsOrdered;

  BasketState(this.itemsOrdered);

  @override
  List<Object> get props => [itemsOrdered]
}

And the following bloc:

class BasketBloc extends Bloc<BasketEvent, BasketState> {
  Map<Item, int> _itemsOrdered = {};
  BasketBloc() : super(BasketState({}));

  @override
  Stream<BasketState> mapEventToState(BasketEvent event) async* {
    if (event is BasketAdd) {
      _itemsOrdered.putIfAbsent(event.item, () => event.amount);
    } else if (event is BasketRemove) {
      _itemsOrdered.remove(event.item);
    }
    yield BasketState(_itemsOrdered);
  }
}

Only the first time I send the BasketAdd event the bloc emits the state, then if I send the BasketAdd event again, the bloc emits nothing.

The only thing that worked is to remove the Equatable from the state, and I dont know why.

Am I doing something wrong?

I recently started using bloc and im stuck here.

I have a state:

class BasketState extends Equatable{
  final Map<Item, int> itemsOrdered;

  BasketState(this.itemsOrdered);

  @override
  List<Object> get props => [itemsOrdered]
}

And the following bloc:

class BasketBloc extends Bloc<BasketEvent, BasketState> {
  Map<Item, int> _itemsOrdered = {};
  BasketBloc() : super(BasketState({}));

  @override
  Stream<BasketState> mapEventToState(BasketEvent event) async* {
    if (event is BasketAdd) {
      _itemsOrdered.putIfAbsent(event.item, () => event.amount);
    } else if (event is BasketRemove) {
      _itemsOrdered.remove(event.item);
    }
    yield BasketState(_itemsOrdered);
  }
}

Only the first time I send the BasketAdd event the bloc emits the state, then if I send the BasketAdd event again, the bloc emits nothing.

The only thing that worked is to remove the Equatable from the state, and I dont know why.

Am I doing something wrong?

From Docs

Equatable properties should always be copied rather than modified. If an Equatable class contains a List or Map as properties, be sure to use List.from or Map.from respectively to ensure that equality is evaluated based on the values of the properties rather than the reference.

yield BasketState(Map<Item, int>.from(itemsOrdered));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM