I am trying to use hydrated bloc to persist my cubit.
But after some trial and error, I found that the loaded state will always be replaced with the initial state
class DefectSectionsCubit extends HydratedCubit<DefectSectionsState> {
DefectSectionsCubit() : super(DefectSectionsState.initial()) {
print("replaced by init");
}
@override
DefectSectionsState? fromJson(Map<String, dynamic> json) {
print("get from json");
return DefectSectionsState.fromMap(json);
}
@override
Map<String, dynamic>? toJson(DefectSectionsState state) {
return state.toMap();
}
}
the "get from json" do get the last state I saved before, but it will soon be replaced with the initial state and therefore the state cannot persist. The output will be:
I/flutter (30280): get from json
I/flutter (30280): replaced by init
you can see the fromJson will be called first and then the constructor, which makes the initial state will always override the loaded state.
My state is like this:
class DefectSectionsState extends Equatable {
final List<DefectSection> defectSections;
const DefectSectionsState({
required this.defectSections,
});
factory DefectSectionsState.initial() => const DefectSectionsState(
defectSections: [
DefectSection(
sectionName: 'FABRIC',
defectItems: [
DefectItem(name: 'Cotton'),
],
),
DefectSection(
sectionName: 'COLOR',
defectItems: [
DefectItem(name: 'Crimson'),
],
),
DefectSection(
sectionName: 'SEWING',
defectItems: [
DefectItem(name: 'Lockstitch'),
],
),
],
);
}
So how to make my state persistent?
Thanks
I am mis-implemented the fromMap
in my state.
So, I solve this by imeplement the proper fromMap
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.