Connecting Events and States
Explore how to connect events and states in Flutter BLoC by implementing local storage interactions. Understand event to state mapping through Add, Remove, and Get Likes events. Gain practical knowledge of using shared_preferences within a LikesBloc class to manage asynchronous state changes in a Star Wars app project.
Now that our events and states are set in place, it’s time to convert events to states. We have three events: GetLikes, AddToLikes, and RemoveFromLikes. All of these events are going to access the local storage to save and get the likes. So first, let’s implement the storage service.
Storage service
We need two functions in the storage service:
save()function: This saves the liked items in the local storageget()function: This gets the liked items from the local storage.
To access the local storage, we’re using the shared_preferences package.
In the save() function, we transform the List<SwapiObject> to a List<String> in line 4. This is necessary because a list of objects can’t be saved in the shared preferences. In line 6, we save the objects list using the key value likes.
In the get() function, we retrieve the likes list from the shared preferences in line 11. If it’s null, we return an empty list. In lines 13–15, we map the objects list to a List<SwapiObject> by decoding each string ...