flutter 如何将带有timestamp字段的firestore文档数据转换为Freezed dart包生成的数据类?

92dk7w1h  于 2022-12-14  发布在  Flutter
关注(0)|答案(3)|浏览(154)

My Dto的结构如下所示-

@freezed
abstract class MessageDto with _$MessageDto{
  factory MessageDto({
    String message,
    @JsonKey(name: 'message_type') String messageType,
    @JsonKey(name: 'sender_id') String senderId,
    @JsonKey(name: 'sent_at') Timestamp sendAt,
    }) = _MessageDto;

  factory MessageDto.fromFirestore(DocumentSnapshot doc) {
    Map<String, dynamic> json = doc.data;
    return MessageDto.fromJson(json);
  }
  factory MessageDto.fromJson(Map<String, dynamic> json) => _$MessageDtoFromJson(json);
}

1.产生器不支援TimeStamp资料类型。
1.当我使用DateTime dataType时,它正在生成代码,但在将documentSnaphot数据解析为
未行程的例外状况:型别'Timestamp'不是型别转换中型别'String'的子型别

db2dz4w8

db2dz4w81#

您可以将自定义的fromJsontoJson函数传递给@JsonKeyhttps://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/JsonKey.html

Timestamp _sendAtFromJson(Timestamp timestamp) => timestamp;

@freezed
abstract class MessageDto with _$MessageDto{
  factory MessageDto({
    String message,
    @JsonKey(name: 'message_type') String messageType,
    @JsonKey(name: 'sender_id') String senderId,
    @JsonKey(name: 'sent_at', fromJson: _sendAtFromJson) Timestamp sendAt,
    }) = _MessageDto;

  factory MessageDto.fromFirestore(DocumentSnapshot doc) {
    Map<String, dynamic> json = doc.data;
    return MessageDto.fromJson(json);
  }
  factory MessageDto.fromJson(Map<String, dynamic> json) => _$MessageDtoFromJson(json);
}
szqfcxe2

szqfcxe22#

最好将时间戳转换为日期时间

// To parse this JSON data, do
//
//     final notificationModel = notificationModelFromJson(jsonString);

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'notification_model.freezed.dart';
part 'notification_model.g.dart';

NotificationModel notificationModelFromJson(String str) =>
    NotificationModel.fromJson(json.decode(str));

String notificationModelToJson(NotificationModel data) =>
    json.encode(data.toJson());

@freezed
abstract class NotificationModel with _$NotificationModel {
  const factory NotificationModel({
    String? title,
    String? uid,
    String? description,
    @JsonKey(name: 'createdOn', fromJson: _sendAtFromJson) DateTime? createdOn,
  }) = _NotificationModel;

  factory NotificationModel.fromJson(Map<String, dynamic> json) =>
      _$NotificationModelFromJson(json);
}

DateTime _sendAtFromJson(Timestamp timestamp) =>
    DateTime.fromMillisecondsSinceEpoch(timestamp.millisecondsSinceEpoch);
ui7jx7zq

ui7jx7zq3#

在我的情况下,仅从json方法是不够的..我想使用毫秒FromEpoch从/到json转换:

Timestamp _timestampFromJson(int timestamp) => Timestamp.fromMillisecondsSinceEpoch(timestamp);
int _timestampToJson(Timestamp timestamp) => timestamp.millisecondsSinceEpoch ;

以及在类型为Timestamp的冻结字段中:

@JsonKey(name: 'key_name', fromJson: _timestampFromJson , toJson: _timestampToJson)

相关问题