【发布时间】:2020-07-02 17:29:17
【问题描述】:
我想从 Firestore 获取会议并将它们映射到以下 Meeting 模型:
part 'meeting.g.dart';
@JsonSerializable(explicitToJson: true)
class Meeting {
String id;
DateTime date;
Meeting(this.id, this.date);
factory Meeting.fromJson(Map<String, dynamic> json) {
return _$MeetingFromJson(json);
}
Map<String, dynamic> toJson() => _$MeetingToJson(this);
}
从 Firestore 获取文档,然后在可迭代对象上调用 fromJson,但抛出异常:
type 'Timestamp' is not a subtype of type 'String' in type cast
当我进入生成的meeting.g.dart 时,正是这一行导致了错误
json['date'] == null ? null : DateTime.parse(json['date'] as String)
为了解决该问题,我尝试在模型中将 DateTime 更改为 Timestamp,但随后显示以下构建错误:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `date`.
None of the provided `TypeHelper` instances support the defined type.
你能告诉我你是如何解决这个问题的吗? 是否有另一种首选方法将 Firebase 和使用 json_serializable 进行 JSON 序列化的 Flutter 项目结合起来?甚至可以替换 json_serializable 的使用?
【问题讨论】:
-
你试过替换
DateTime.parse(json['date'] as String)。与DateTime.parse(json['date'].toString()) -
我认为编辑生成的文件不是一个好习惯。每次模型更改时我都必须这样做,因为会重新生成 meeting.g.dart。
-
你可能需要手动序列化 json,看看这篇帖子stackoverflow.com/a/58309472/9609442
-
在生产中的应用程序中,我在上传之前将日期线解析为字符串,然后在获取时将其转换回日期时间。
-
你在 json['date'] 中得到了什么?是 millisecondsSinceEpoch 还是 dateString?
标签: flutter dart google-cloud-firestore