Nicolas Le Bot
Nicolas Le Bot

Reputation: 334

How to stock list with Hive in Flutter?

I'm looking to stock some lists into Hive.

In my main.dart, I got:

Hive.registerAdapter(MedicalConstantsAdapter());
await Hive.openBox(MEDICAL_CONSTANTS);

In my medical.dart, I got:

@HiveType(typeId: 0)
class MedicalConstants extends HiveObject {
  @HiveField(0)
  List<SystolicPressure> systolicPressure;
  @HiveField(1)
  List<DiastolicPressure> diastolicPressure;

  MedicalConstants({
    this.systolicPressure,
    this.diastolicPressure
  });

  MedicalConstants.fromJson(Map<String, dynamic> json) {
    if (json['systolic_pressure'] != null) {
      systolicPressure = new List<SystolicPressure>();
      json['systolic_pressure'].forEach((v) {
        systolicPressure.add(new SystolicPressure.fromJson(v));
      });
    }
    if (json['diastolic_pressure'] != null) {
      diastolicPressure = new List<DiastolicPressure>();
      json['diastolic_pressure'].forEach((v) {
        diastolicPressure.add(new DiastolicPressure.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.systolicPressure != null) {
      data['systolic_pressure'] =
          this.systolicPressure.map((v) => v.toJson()).toList();
    }
    if (this.diastolicPressure != null) {
      data['diastolic_pressure'] =
          this.diastolicPressure.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class MedicalConstantsAdapter extends TypeAdapter<MedicalConstants> {
  @override
  final typeId = 1;

  @override
  MedicalConstants read(BinaryReader reader) {
    return MedicalConstants()
      ..diastolicPressure
      ..systolicPressure = reader.read();
  }

  @override
  void write(BinaryWriter writer, MedicalConstants obj) {
    writer
      ..write(obj.systolicPressure)
      ..write(obj.diastolicPressure);
  }
}

And to finish, in my session.dart, I got:

Hive.box(MEDICAL_CONSTANTS).values.toList().forEach((element) {
  print(element);
});

The 2 list I'm getting are from my endpoint and datas stock in the list already.

I just for the moment display my result to the print.

I tried to use the command from hive flutter packages pub run build_runner build, but nothing happened, and that's why maybe my MedicalConstantsAdapter is not build properly?

Is there someone with an idea how to use it properly?

Upvotes: 1

Views: 7520

Answers (1)

Mensch
Mensch

Reputation: 700

medical.dart


// add 'g' to file name to indicate generated
part 'medical.g.dart'

@HiveType(typeId: 0)
class MedicalConstants extends HiveObject {
  @HiveField(0)
  List<SystolicPressure> systolicPressure;
  @HiveField(1)
  List<DiastolicPressure> diastolicPressure;

  MedicalConstants({
    this.systolicPressure,
    this.diastolicPressure
  });
}

The type adapter will be then generated to medical.g.dart once you run

flutter packages pub run build_runner build

Upvotes: 2

Related Questions