Home > Enterprise >  How to generate a datetime in model using flutter freezed package
How to generate a datetime in model using flutter freezed package

Time:12-07

I have this freezed part

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_model.freezed.dart';
part 'user_model.g.dart';

@freezed
class UserModel with _$UserModel {
  factory UserModel({
    required String id,
    @Default('') String uniqueId,
    @Default(DateTime.now()) DateTime dob,

  }) = _UserModel;

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

But am not able to generate the required file due to DateTime.now().

if I do something like this:

factory UserModel({
        required String id,
        @Default('') String uniqueId,
        required DateTime dob,
    
      }) = _UserModel;

it will work but I have to manually edit the generated data to this:

dob: (json['dob'] as Timestamp?)?.toDate() ?? DateTime.now()

from

dob: DateTime.parse(json['dob'] as String),

I can't keep manually editing it all time.

Please how do I generate the model class including Datetime.

CodePudding user response:

you need to manually add serialization logic in your freezed model class.

In this specific situation, you need firestore timestamp serialization logic.

Just add

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

class TimestampSerializer implements JsonConverter<DateTime, dynamic> {
  const TimestampSerializer();

  @override
  DateTime fromJson(dynamic timestamp) => timestamp.toDate();

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

and add TimestampSerializer() annotation for your DateTime property like this.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_model.freezed.dart';
part 'user_model.g.dart';

@freezed
class UserModel with _$UserModel {
  factory UserModel({
    required String id,
    @Default('') String uniqueId,
    @TimestampSerializer() required DateTime dob,

  }) = _UserModel;

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

and then finally run build runner. You are good to go.

Hope it helps! Happy coding:)

  • Related