gpt4 book ai didi

flutter - 如何在类型转换中解析 'Timestamp'类型不是 'String'类型的子类型

转载 作者:行者123 更新时间:2023-12-03 02:44:12 24 4
gpt4 key购买 nike

我想从Firestore中获取 session 并将其映射到以下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和Flutter项目结合使用json_serializable进行JSON序列化?甚至可以替换json_serializable的用法?

最佳答案

使用JsonConverter

class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
const TimestampConverter();

@override
DateTime fromJson(Timestamp timestamp) {
return timestamp.toDate();
}

@override
Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
}

@JsonSerializable()
class User{
final String id;
@TimestampConverter()
final DateTime timeCreated;

User([this.id, this.timeCreated]);

factory User.fromSnapshot(DocumentSnapshot documentSnapshot) =>
_$UserFromJson(
documentSnapshot.data..["_id"] = documentSnapshot.documentID);

Map<String, dynamic> toJson() => _$UserToJson(this)..remove("_id");
}

关于flutter - 如何在类型转换中解析 'Timestamp'类型不是 'String'类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com