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

Time:11-25

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.

CodePudding user response:

I think this is a problem with the package because I have the same issue that everything works okay but with restarting the app the data disappears. So I asked the question at hive flutter github and no answers yet. So I ask u to open an issue at hive flutter github to let them know that this is a real problem we face it.

CodePudding user response:

I try this method and it works for me as list doesn't require register an adaptor.

await Hive.openBox<List>(bookmarks);

add data like this

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

and you can access data via ValueListenableBuilder

if u need more explanation please comment.......

  • Related