【问题标题】:Map of object containing a List<Object> for sqlite包含用于 sqlite 的 List<Object> 的对象映射
【发布时间】:2020-05-29 23:50:10
【问题描述】:

我正在设置我的模型类以确认 sqflite 的文档,该文档建议包括一个命名构造函数来转换为地图/从地图转换,以更好地处理类和数据库之间的数据。我能找到的每个示例都非常简单,类属性都是简单的数据类型。

使用下面显示的构造函数和方法,在处理诸如此类的类时,与 Map 之间的转换非常简单。

class Human{
  final String name;
  final String height;
  Final String weight;

  Human({this.name, this.height, this.weight});
}

但是,当你有一个类中的一个字段有点复杂时,我不明白如何在命名构造函数和 xxx 方法中构造事物以返回我“相信”我应该得到的数据映射.

class Human{
      final String name;
      final String height;
      Final String weight;
      List<Child> children = [];

      Human({this.name, this.height, this.weight, this.children});
    }

Human({this.name, this.height, this.weight, this.children});

  Human.fromMap(Map<String, dynamic> map)
    : name = map['name'],
      height = map['height'],
      weight = map['weight'],
      children = map['children'];

  Map<String, dynamic> toMap() {
   return {
     'name': name,
     'height': height,
     'weight': weight,
     'children': children,
   }; 
  }

列出孩子是我正在努力解决的部分。我相信您必须将每个子对象也转换为父地图中的地图,但在这里输掉了这场战斗。

我的方法是不是在这里?我应该使用其他方法来完成此操作吗?

任何帮助将不胜感激。

【问题讨论】:

  • 你能分享你的孩子班吗?

标签: flutter dart


【解决方案1】:

这里我解释一下

  1. 如何将模型对象转换为 Map 以与 sqlite 一起使用
  2. 如何将 Map 对象从 sqlite 转换为模型类。
  3. 如何在 Flutter 中正确解析 JSON 响应
  4. 如何将模型对象转换为 JSON

以上所有问题都有相同的答案。 Dart 对这些操作有很大的支持。这里我将用一个详细的例子来说明它。

class DoctorList{
  final List<Doctor> doctorList;

  DoctorList({this.doctorList});

  factory DoctorList.fromMap(Map<String, dynamic> json) {
    return DoctorList(
      doctorList: json['doctorList'] != null
          ? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
          : null,
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    if (this.doctorList != null) {
      data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
    }
    return data;
  }
}

上面的DoctorList 类有一个成员,它包含一个“Doctor”对象列表。

看看我是如何解析医生列表的。

 doctorList: json['doctorList'] != null
      ? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
      : null,

您可能想知道,Doctor 类可能是什么样子。给你

class Doctor {
  final String doCode;
  final String doctorName;

  Doctor({this.doCode, this.doctorName});

  factory Doctor.fromMap(Map<String, dynamic> json) {
    return Doctor(
      doCode: json['doCode'],
      doctorName: json['doctorName'],
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['doCode'] = this.doCode;
    data['doctorName'] = this.doctorName;
    return data;
  }

}

就是这样。希望你明白了。干杯!

【讨论】:

  • 太棒了,谢谢你的解释。非常清楚,非常感谢。
  • 如果可以的话,有一个后续问题。在下面...
  • @bboursaw73 将其作为一个新问题发布,我们将看看
猜你喜欢
  • 1970-01-01
  • 2017-03-05
  • 2022-07-26
  • 2014-01-04
  • 1970-01-01
  • 2015-06-11
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多