flutter 来自服务器的数据未分配给变量

llycmphe  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(518)

我正在从服务器获取数据。我接收数据,并在DrinkModel.fromJson的帮助下接收数据。数据被分配给value和timestamp变量。但是addDrinkWater变量被设置为null。为什么会出现这样的错误?如果数据来到我这里,并且它们在DrinkModel中被分配。

settings_model

@HiveType(typeId: 1)
class SettingsModel extends HiveObject {

  @HiveField(13)
  DrinkModel? addDrinkWater;

  SettingsModel({
    this.addDrinkWater,
  });

  SettingsModel.fromJson(Map<String, dynamic> json) {
    addDrinkWater = AddDrinkModel.fromJson(json['_counter']);
  }

drink_model

@HiveType(typeId: 48)
class AddDrinkModel extends HiveObject {
  AddDrinkModel({
    required this.value,
    required this.timestamp,
  });

  @HiveField(0, defaultValue: 0)
  late int value;

  @HiveField(1, defaultValue: 1)
  late int timestamp;

  AddDrinkModel.fromJson(Map<String, dynamic> json) {
    value = json['value'] ?? 0;
    timestamp = DateTime.parse(DateTime.parse(
                json['timestamp'] ?? DateTime.now().millisecondsSinceEpoch)
            .toIso8601String())
        .millisecondsSinceEpoch;
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['value'] = value;
    data['timestamp'] =
        DateTime.fromMillisecondsSinceEpoch(timestamp).toString();
    return data;
  }
}

json

"settings": {
            "_counter": {
                "value": 0,
                "timestamp": "2023-06-06T13:27:36.627Z"
            },

保存AddDrinkModel中的数据

不保存addDrinkWater变量中的数据

ycl3bljg

ycl3bljg1#

AddDrinkModel.fromJson(Map<String, dynamic> json) {
value = json['value'] ?? 0;
timestamp = DateTime.parse(DateTime.parse(
            json['timestamp'] ?? DateTime.now().millisecondsSinceEpoch)
        .toIso8601String())
    .millisecondsSinceEpoch;
return AddDrinkModel(value, timestamp);

}
你是不是错过了一个回报?(不习惯与hive一起工作,除非它改变了这一点,似乎回报对我来说是缺失的)

相关问题