firebase - 如何在 Flutter 中有字段 Timestamp 的类“flutter pub run build_runner build”?
问题描述
我正在尝试使用 cmd“flutter pub run build_runner build”从对象序列化 JSON 格式,但它一直在显示消息:
运行 JsonSerializableGenerator 时出错 无法fromJson
为timeTaking
. TypeHelper
提供的实例都不支持定义的类型。
@JsonSerializable(explicitToJson: true)
class RequestData {
@JsonKey(required: true)
String uid;
String phone;
String email;
String description;
/// Tell json_serializable that "owner_name" should be
/// mapped to this property.
@JsonKey(name: 'owner-name')
String ownerName;
@JsonKey(name: 'location-detail')
String locationDetail;
int status;// 0 waiting, 1 accepted, 2 done, 3 DOING , 4 cancel
List<String> imageUrls;
@JsonKey( required: true, name: "time-taking", toJson: _timestampToJson/*,fromJson: _timeStampFromJson*/)
Timestamp timeTaking;
RequestData({this.uid, this.phone, this.email, this.description,
this.ownerName, this.locationDetail, this.status, this.imageUrls,this.timeTaking});
RequestData.none();
}
我该如何解决这个问题?
解决方案
我有同样的问题,我的临时解决方案是创建一个 JsonConverter 来转换为 DateTime:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';
class TimestampConvertDatetime implements JsonConverter<DateTime, Timestamp> {
const TimestampConvertDatetime();
@override
DateTime fromJson(Timestamp json) {
return json.toDate();
}
@override
Timestamp toJson(DateTime object) {
return Timestamp.fromDate(object);
}
}
并应用于您的模型:
...
@TimestampConvertDatetime()
DateTime date;
....
推荐阅读
- django-rest-framework - 谷歌登录在 django rest 框架 + allauth + rest-auth
- django - DRF 令牌身份验证:{“详细信息”:“未提供身份验证凭据。” }
- php - 如何将数据库中的数据作为数组调用,然后回显数组中的每个值?
- google-sheets-formula - 在现有公式中增加图纸编号
- sql - Laravel 查询 - 从 3 个不同的表中计数和分组
- symfony - Symfony 4 和 Mercure 与 Docker - 无法连接到服务器
- python - Django ValueError - 没有足够的值来解包(预期 2,得到 1)元组错误列表
- python - 如何绕过 Python 请求“请求远程结束关闭连接而没有响应”的错误
- php - SQL Server查询返回输出参数为空白数组
- bash - 提取数字并使用 sed 重新插入