skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    I am mis-implemented the fromMap in my state.

    So, I solve this by imeplement the proper fromMap


  2. I battled with this issue for some time, and I found the cause to be two issues:

    • I was not calling hydrate(); inside my bloc constructor.
    • fromJson was throwing an error but not explicitly showing it on the console, this error was due to some null values that were not handled properly.

    I hope this help, thanks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search