How to convert firestore doc data having timestamp field into the data class generated through Freezed dart package?

Viewed 1118

Structure of My Dto is like -

@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. The generator is not supporting TimeStamp data type.
  2. When I am using DateTime dataType, it is generating code but throwing exception on parsing the documentSnaphot data as

Unhandled Exception: type 'Timestamp' is not a subtype of type 'String' in type cast

2 Answers

You can pass a custom fromJson and toJson function to the @JsonKey. https://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);
}

Its better to convert the timestamp to datetime

// 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);

Related