简体   繁体   中英

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

my flutter app has a class "Cart" which has one string value ie 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM