Hassan Ansari
Hassan Ansari

Reputation: 314

How can I upload a List<Class> to cloud firestore?

my flutter app has a class "Cart" which has one string value i.e name of order, and one is an int value which is the quantity of order. When I add an item to cart, it will be added to a List (using provider) so how can I upload that List to firestore.

Upvotes: 0

Views: 335

Answers (1)

J. S.
J. S.

Reputation: 9635

You can have methods in your class to transform to and from a Map and then store the JSON string in Firestore:

class Cart{
  String name;
  int quantity;

  Cart({
    this.name,
    this.quantity,
  });

  Cart.fromMap(Map<String, dynamic> map) :
    name = map['name'],
    quantity = map['quantity'];

  Map toMap(){
    return {
      'name': name,
      'quantity': quantity,
    };
  }
}

Then you can encode the results of the methods to JSON:

json.encode(Cart.toMap());

Cart.fromMap(json.decode(cartStringFromFirestore))

Upvotes: 2

Related Questions