Bloc: Bloc doesn't see the difference in states

Created on 11 Feb 2020  路  4Comments  路  Source: felangel/bloc

  1. I have a state with a List:
class MyState extends Equatable {
  List<IItem> items;

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

I need to delete one item from this list and add another, and then yield new state:

state.items.remove(item);
state.items.insertAll(0, anotherItem);
yield MyState(state.items);

But, unfortunately, BlocBuilder does not react to the new state. I also tried to insert more than one item(so length of the list before deleting and after inserting doesn't match), and use ...items in the MyState.get, nothing helped. Also, IItem extends Equatable.
I understand that bloc thinks that it is the same state, but why? And how can I fix it?

  1. I know that BlocListener is guaranteed to only be called once for each state change. But let's assume that the user enters the wrong password, bloc will generate something like ErrorState with "Wrong password!" String, BlocListener will catch it and show SnackBar. But after this user enters the wrong password again, now BlocListener doesn't catch it.
    What workaround should be used in this situation?
question

Most helpful comment

@felangel Hmm.. yep, that makes sense, so easy :D
Thanks!

All 4 comments

Hi @don-prog 馃憢
Thanks for opening an issue!

Bloc only works with immutable state which means rather than mutating your state you must create a copy of your state.

yield MyState(
  List.from(state.items)
    ..remove(item)
    ..insertAll(0, anotherItem)
);

Also, please make sure that IItem also extends Equatable and overrides props correctly 馃憤

Hope that helps!

@felangel ok, thanks. I thought that creating a new state would be enough, but now I see that the List also needs to be recreated.
And what about the second question about BlocListener scenario?

Ah sorry missed the second part. In that case your ErrorState shouldn't extend Equatable.

@felangel Hmm.. yep, that makes sense, so easy :D
Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wheel1992 picture wheel1992  路  3Comments

abinvp picture abinvp  路  3Comments

shawnchan2014 picture shawnchan2014  路  3Comments

nerder picture nerder  路  3Comments

clicksocial picture clicksocial  路  3Comments