HydratedCubit A specialized Cubit which handles initializing the Cubit state based on the persisted state. This allows state to be persisted across application restarts.
With HydratedCubit you can load JSON data and store JSON data locally.
Your HydratedCubit class may look like this
class WorkoutsCubit extends HydratedCubit<List<Workout>> {
WorkoutsCubit() : super([]);
}
Since you want to manage storage using HydratedCubit, your Cubit class must extend HydratedCubit. If you extend HydratedCubit, then you must override two methods.
Your normal Cubit class could be easily replaced by HydratedCubit class.
fromJson() and toJson() methods.
@override
List<Workout> fromJson(Map<String, dynamic> json) {
........
........
return workouts;
}
fromJson() method automatically gets called when you restart your app. It does not get called when you first time install the app.
This method fromJson() get’s called to convert the JSON info to an object. In general your class needs to use a lot of objects.
But subsequent states change may cause this method to be called.
@override
Map<String, dynamic>? toJson(List<Workout> state) {
..........
..........
return json;
}
This toJson() method gets called when the app gets installed first time. It gets called before any other method or states that has to do with BLoC or Cubit.
This toJson() method gets called even before the states are initialized. After states are emitted toJson() method gets called again and it’s a place for checking on the states and do something.
toJson() method gets called since you want to store data or state to the device. So Cubit should convert the data to JSON format, toJson() method does the job.
The idea is that, you have to emit() states first, once the states are emitted toJson() will get called automatically.
Since toJson() method helps you store states or data, you need to store in a Map type variable.
You need to call HydratedCubit class from BlocBuilder. It’s just like calling a normal Cubit class from BlocBuilder.