Flutter Firestore Server side Timestamp

If you are using a model class to set the data, then you should create a dynamic variable with some name. For mine it was 'createdDate'.

class Products {
  Products({
    this.data,
    this.createdDate,
  });

  List<ProductItems>? data;
  dynamic createdDate;

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        data: List<ProductItems>.from(json["data"].map((x) => ProductItems.fromJson(x))),
        createdDate: json["createdDate"],
      );

  Map<String, dynamic> toJson() => {
        "data": List<dynamic>.from(data!.map((x) => x.toJson())),
        "createdDate": createdDate
      };
}

class ProductItems {
  String? id;
  String? name;
  int? price;
  int? quantity;

  ProductItems({
    this.price,
    this.quantity,
    this.name,
    this.id,
  });

  ProductItems.fromJson(Map<String, dynamic> json) {
    price = json['price'];
    quantity = json['quantity'];
    name = json['name'];
    id = json['id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['price'] = price;
    data['quantity'] = quantity;
    data['name'] = name;
    data['id'] = id;
    return data;
  }
}

And during setting the data to firestore,

    final CollectionReference _cart = _firestore.collection('cart');

    final _cartReference = _cart.withConverter<Products>(
      fromFirestore: (snapshot, _) => Products.fromJson(snapshot.data()!),
      toFirestore: (userModel, _) => userModel.toJson(),
    );

    await _cartReference.doc(auth?.uid).set(Products(
      data: productList.data,
      createdDate: FieldValue.serverTimestamp(),
    ));

As of September 5th, the updated cloud_firestore v0.8.0 library now has FieldValue.serverTimestamp(). All is now well in the universe


Expanding on @spongyboss' answer (which works as of April 2020) by adding sample usage:

_firestore.collection('messages').add({
                      'text': messageText,
                      'sender': loggedInUser.email,
                      'created': FieldValue.serverTimestamp()
                  });

'created' will be stored as a timestamp

Sample sorting:

_firestore.collection('messages')
          .orderBy('created', descending: false)
          .snapshots()

'timestamp' : Timestamp.now()

Timestamp.now() is part of cloud_firestore;


Example enter image description here Screenshot showing that the library is imported from cloud_firestore, and creates a server-generated timestamp in the written data. Docs