Connecting Events and States
Connect event classes and state classes together using tools provided by the flutter_bloc library.
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.
class StorageService {Future<void> save(List<SwapiObject> value) async {SharedPreferences prefs = await SharedPreferences.getInstance();List<String> objects = value.map((e) => json.encode(e.toJson())).toList();await prefs.setStringList('likes', objects);}Future<List<SwapiObject>> get() async {SharedPreferences prefs = await SharedPreferences.getInstance();List<String> objects = prefs.getStringList('likes') ?? [];return objects.map((e) {return SwapiObject.fromJson(json.decode(e));}).toList();}}
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 ...