Flutter Hive save custom object with list of custom objects gone after restarting app

418

Solution 1

If you're saying data is being saved and everything worked fine till you didn't restart the app. So the problem may be : After restarting your app, you had may put a function that cleared all the data saved in Hive as soon as app starts. Check this one.If like this will there then remove that line or function that clear all the data from hive DB.

Solution 2

I use this method and it works for me as List doesn't require registering an adapter:

await Hive.openBox<List>(bookmarks);

Add data like this:

boxValue.put(index, [
                    question.title,
                    question.options,
               ],
);

And you can access the data via ValueListenableBuilder.

Share:
418
Chris
Author by

Chris

Updated on January 02, 2023

Comments

  • Chris
    Chris over 1 year

    I am using the Hive- Package in my project to store some data locally. That has been working fine so far, but now I am facing an issue:

    I have a Custom-Class which also has a field with another Custom-Class:

    part 'hive_vitals_interface.g.dart';
    
    @HiveType(typeId: 1)
    class HiveVitals extends HiveObject {
      @HiveField(0)
      String? id;
      @HiveField(1)
      DateTime? date;
      @HiveField(2)
      List<HiveDiscomfort> otherDiscomfort;
      @HiveField(3)
      List<HiveDiscomfort> mentalDiscomfort;
    
      HiveVitals({
        this.id,
        this.date,
        this.otherDiscomfort = const [],
        this.mentalDiscomfort = const [],
      });
    }
    

    And my HiveDiscomforts-Class:

    part 'hive_discomfort_interface.g.dart';
    
    @HiveType(typeId: 2)
    class HiveDiscomfort extends HiveObject {
      @HiveField(0)
      String? title;
      @HiveField(1)
      int? intensity;
    
      HiveDiscomfort({
        this.title,
        this.intensity,
      });
    }
    

    I am trying to save HiveVitals like this:

      static Future<void> addVitals(HiveVitals hiveVitals) async {
        final vitalsBox = getVitalsBox();
    
        await vitalsBox.put(hiveVitals.date!.toIso8601String(), hiveVitals);
    
      }
    

    And retrieve it like this:

      static List<HiveVitals> getVitals() {
        Box<HiveVitals> box = getVitalsBox();
        List<HiveVitals> hiveVitals = box.values.toList();
        return hiveVitals;
      }
    

    Problem:

    I don't get any errors. In fact when saving my object and checking it in the debugger, everything is saved correctly. However when restarting the app, my List<HiveDiscomfort> fields are always empty again! But the rest of the HiveVitals-Fields are still saved correctly!?

    What am I missing here? I don't get it... Any help is appreciated! Let me know if you need anything else!

    Also opened an issue on Github.