包含<Object> sqlite 列表的对象映射



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

使用下面显示的构造函数和方法,在处理此类类时,与 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,
}; 
}

名单儿童是我正在努力解决的部分。 我相信您必须将每个 Child 对象也转换为父地图中的地图,但在这里输掉了战斗。

我的方法离这里很远吗? 我应该使用其他方法来完成此操作吗?

任何协助将不胜感激。

在这里我解释以下内容

  1. 如何将模型对象转换为 Map 以与 sqlite 一起使用
  2. 如何将 Map 对象从 sqlite 转换为模型类。
  3. 如何在颤振中正确解析 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;
}
}

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

最新更新