flutterhivelocal-storageflutter-hive

hive data gets reset when app is restarted


I have stored data in Hive box but whenever i restart the app or kills the app during offline mode i.e when internet conmnection is not there, Data gets resets & shows null error.

  await Hive.initFlutter();
  Hive.registerAdapter<ProgressList>(ProgressListAdapter());
  Hive.registerAdapter<VideoList>(VideoListAdapter());
  Hive.registerAdapter<DashBoard>(DashBoardAdapter());
  Hive.registerAdapter<CourseDetails>(CourseDetailsAdapter());
  Hive.registerAdapter<AnnouncementsListData>(AnnouncementsListDataAdapter());
  Hive.registerAdapter<VideoAssignments>(VideoAssignmentsAdapter());
  Hive.registerAdapter<LessonDetail>(LessonDetailAdapter());
  Hive.registerAdapter<CourseQuestions>(CourseQuestionsAdapter());
  await Hive.openBox<ProgressList>("box");
  await Hive.openBox<VideoList>("video_box");
  await Hive.openBox<DashBoard>("dashboard_box");
  await Hive.openBox<CourseDetails>("course_box");
  await Hive.openBox<AnnouncementsListData>("announcement_box");
  await Hive.openBox<VideoAssignments>("vfs_feedback_box");
  await Hive.openBox<LessonDetail>("lesson_box");
  await Hive.openBox<CourseQuestions>("questions_box");
  await Hive.openBox("video_record_box");

Solution

  • Make sure you are passing all parameters of the models to the constructor, for example in the code below

    @HiveType(typeId: 22)
    class WeeklyListModel extends HiveObject {
      @HiveField(0)
      final String id;
    
      @HiveField(1)
      final List<TaskModel> tasks = [];
    
      WeeklyListModel(this.id);
    }
    

    The read function of adapter will look like this

    @override
      WeeklyListModel read(BinaryReader reader) {
        final numOfFields = reader.readByte();
        final fields = <int, dynamic>{
          for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
        };
        return WeeklyListModel(
          fields[0] as String
        );
      }
    

    So the tasks are automatically set to empty list as they can not be passed to the constructor.