firebase - Firestore 文档中的数组类型字段将转换为自定义对象列表
问题描述
我想将 LIST_OF_ALL_COLLEAGUES 转换为 List 但我无法弄清楚如何去做。
我有一个用户类,它有这个 List 同事字段。我的用户类转换代码如下所示:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';
import 'package:snagsnapper/Data/colleague.dart';
class User {
User ({
this.name,
this.dateFormat,
this.listOfALLColleagues,
});
String name;
String dateFormat='dd-MM-yyyy';
List<Colleague> listOfALLColleagues;
User.fromMap(DocumentSnapshot data)
: this(
name: data[NAME],
dateFormat: data[DATE_FORMAT],
listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
);
Map<String, dynamic> toJSON() => {
NAME : name,
DATE_FORMAT : dateFormat,
LIST_OF_COLLEAGUES : listOfALLColleagues,
};
}
我的同事类如下所示:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';
class Colleague {
String name;
String email;
String phone;
String uniqueID;
Colleague({
this.name,
this.email,
this.phone,
this.uniqueID,
});
Colleague.fromMap(DocumentSnapshot data)
: this(
name: data[NAME],
email: data[EMAIL],
phone: data[PHONE],
uniqueID: data[UID],
);
Map<String, dynamic> toJSON() => {
NAME : name,
EMAIL : email,
PHONE : phone,
UID : uniqueID,
};
}
到目前为止,我已经尝试了几种我在网上看到的方法,但没有运气:我尝试过:
listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.castFrom(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: data[LIST_OF_COLLEAGUES] as List<Colleague>,
listOfALLColleagues: data[LIST_OF_COLLEAGUES]
.map((value) {
return Colleague.fromMap(value);
}).toList(),
我知道其中一些是相同的,但我只想在这里提及它们。
解决方案
我设法用 Json-Serial 库做到了。我之前并不知道这个库,我发现这样更容易。
推荐阅读
- r - 为什么 R 代码可以在本地工作,但不能在 Docker 中运行?
- state-machine - 有没有办法在 xState 的层次状态节点中进行保护转换
- php - MAMP 上的 cURL 不工作,但相同的脚本在 Apache 的服务器上工作
- bash - 为什么在 VLC 的 DBus 中使用 Seek 方法会出现这么多错误?
- python - 将格式化为 Pandas DataFrame 的字符串转换为实际的 DataFrame
- python - 如何使用熊猫获取数据框列(具有字符串数组)中每个元素的频率?
- bash - 使用 Shell 脚本在新文件中打印带有一些文本的日期
- powershell - SharePoint Online 更改外观主题不起作用
- php - 如何使用正则表达式按字符拆分字母数字字符串?
- docker - 允许 Docker 容器仅与主机通信