LoginSignup
3
1

More than 3 years have passed since last update.

Flutter×FireStoreでのTimestampの扱い(toJson,fromJson)

Last updated at Posted at 2021-01-31

FireStoreにTimeStamp型のデータを保存する場合、jsonのシリアライズ・デシリアライズにDateTime型とは異なる対応が必要。

モデルクラスにJsonKeyをつける

  @JsonKey(fromJson: fromTimeStampJson, toJson: toTimeStampJson)
  Timestamp date;

toJson (シリアライズ)

Map<String, dynamic> toTimeStampJson(Timestamp timestamp) {
  return {'date': timestamp.toDate().toIso8601String()};
}

fromJson (デシリアライズ)

Timestamp fromTimeStampJson(Map<String, dynamic> json) {
  final date = DateTime.parse(json['date'] as String);
  return Timestamp.fromDate(date);
}

ちなみにパッケージには、
https://pub.dev/packages/json_serializable
https://pub.dev/packages/json_annotation
https://pub.dev/packages/build_runner
の3つを使用している。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1