Hydrated Bloc not persisting

Viewed 247

I'm trying to get my state to persist using hydrated bloc but it is not working. When i restart the app the state is not persisting

This is the code i have to start the app:

void bootstrap() async {
  WidgetsFlutterBinding.ensureInitialized();
  final storage = await HydratedStorage.build(
    storageDirectory: await getApplicationDocumentsDirectory(),
  );
  HydratedBlocOverrides.runZoned(
    () => runApp(
      RepositoryProvider<void>(
        create: (context) => DatabaseCubit(),
        child: const RunApp(),
      ),
    ),
    storage: storage,
  );
}

this is the relevent code in the cubit:

class DatabaseCubit extends HydratedCubit<DatabaseState>{
  DatabaseCubit() : super(databaseInitial);

  @override
  DatabaseState? fromJson(Map<String, dynamic> json) {
    return DatabaseState.fromMap(json);
  }

  @override
  Map<String, dynamic> toJson(DatabaseState state) {
    return state.toMap();
  }

I have set up unit tests that make sure my toMap and fromMap functions are working. The tests are passing, here is the code for them:

test('Database state should be converted to and from json', () {
      final databaseStateAsJson = databaseState.toMap();
      final databaseStateBackToNormal =
          DatabaseState.fromMap(databaseStateAsJson);
      expect(databaseStateBackToNormal, databaseState);
    });

Please tell me what i am doing wrong

1 Answers

I've just solved a similar problem.

Try digging a little into hydrated_bloc.dart hydrate() method and you might find out why it refuses to load your state :).

Could be type conversion problem between collections - as it was in my case.

Related