Bloc: CurrentState is magically changing?

Created on 11 Nov 2020  路  2Comments  路  Source: felangel/bloc

Hello, thanks for this plugin.

I'm experiencing a strange issue where the BLoCBuilder is not updating due to currentState == nextState, which is of course correct but i'm not sure why currentState is being changed in my case.

I have this Bloc event:

if (event is RemovePhrase) {
phraseRepo.removePhrase(event.phrase);
phrases.remove(event.phrase);
yield GetPhraseLoaded(phrases);
}

phrases is my local list representing a list in a Database.

The use case:
A list of phrases is retrieved and displayed to the user by yielding GetPhraseLoaded, then a phrase is clicked which adds the RemovePhrase event. The phrase is removed and GetPhraseLoaded is yielded again. However as you can see in the image screen shot the nextState and currentState has the same phrase:
image

It is expected that nextState should have 2 phrases, and that currentState should have 1.

Why is currentState changed here?

Please let me know if i can clarify anything.

question

All 2 comments

Hi @carekb684 馃憢
Thanks for opening an issue!

I believe this is happening because you are mutating state and maintaining internal bloc state. I would highly recommend avoiding maintaining an internal phrases in your bloc and I would also highly recommend not mutating state directly like:

phrases.remove(event.phrase);

Instead, I would recommend creating a new instance like:

final newPhrases = List.of(state.phrases)..remove(event.phrase);
yield GetPhraseLoaded(newPhrases);

Hope that helps 馃憤

Thank you!

Was this page helpful?
0 / 5 - 0 ratings