如何在Flutter与Hive库存清单?

szqfcxe2  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(443)

我想把一些清单存进Hive。
在我的main.dart中,我得到了:

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

在我的医疗记录里,我得到了:

@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);
  }
}

最后,在我的会话中。达特,我得到:

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

我得到的2个列表是从我的终点和数据库存在列表中已经。
我只是暂时把我的结果展示给印刷品。
我试着使用Hive中的命令“flutter packages pub run build\u runner build”,但是什么都没发生,这就是为什么我的医疗约束适配器没有正确构建的原因?
有人知道如何正确使用它吗?

hkmswyz6

hkmswyz61#

医疗.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
  });
}

然后将生成类型适配器以 medical.g.dart 一旦你跑了

flutter packages pub run build_runner build

相关问题