How to "flutter pub run build_runner build" with the class has field Timestamp in Flutter?

666

I have the same issue, my temporary solution is create a JsonConverter to convert to 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);
  }
}

And apply on your model:

...
@TimestampConvertDatetime()
DateTime date;
....
Share:
666
Hoang Trung Nguyen
Author by

Hoang Trung Nguyen

Updated on December 19, 2022

Comments

  • Hoang Trung Nguyen
    Hoang Trung Nguyen over 1 year

    I am trying to use the cmd "flutter pub run build_runner build" to serialize the JSON format from object but it keeps plaining with the message:

    Error running JsonSerializableGenerator Could not generate fromJson code for timeTaking. None of the provided TypeHelper instances support the defined type.

    @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();
    }
    

    How do I solve this problem?

  • Hoang Trung Nguyen
    Hoang Trung Nguyen about 4 years
    Cool! Let's try this solution.