Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

Serializing DateTime to Timestamp for firestore flutter

i have a model class

import 'package:cloud_firestore/cloud_firestore.dart';

class Available{
 String uid;
 DateTime date;
 int stock;
 bool isAvailable;

 Available({this.date,this.uid,this.stock,this.isAvailable});


  Available.fromJson(Map<String, dynamic> json)
       : uid = json['UID'],
       date = DateTime.parse(json['date'].toDate().toString()),
     stock = json['stock'],
    isAvailable = json["isAvailable"];

 Map<String, dynamic> toJson() {
   return {
    'UID': uid,
    'date': date,
    'stock': stock,
    'isAvailable': isAvailable,
   };
 }
}

and i have a list of Available objects and when i try to encode the list to json and store it to firestore i can't seem to do it because of the DateTime object

Note : am updating the entire list like so :

var json = jsonEncode(value.map((e) => e.toJson()).toList(),toEncodable: myDateSerializer);

    FirebaseFirestore.instance.collection("Availability").doc(element.pid).update({
      "dates":jsonDecode(json)
    });

but i need all the dates for each object to be stored as firestore timestamp so using date.toIso8601String() or date.microsecondsSinceEpoch will not work as it won't be firestore timestamp format .

question from:https://stackoverflow.com/questions/65914914/serializing-datetime-to-timestamp-for-firestore-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

At least with Firebase you can store a DateTime object directly.

I think you are doubling the json markup with your update. Just pass the date with update: update({"dates":myDate


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...