Flutter Save a LIST of data to FireStore

Viewed 2008

I have a simple Shopping Cart App. The cart is a List of a model called "CartItem"

 List<CartItem> _cart= [];

and the Cart Model:

     class CartItem{
          String name;
          double singlePrice;
          double quantity;
     
   CartItem({
            this.name,
            this.singlePrice,
            this.quantity
        } );

After adding products to the cart, How can I save the entire Cart in Firestore? for Example, lets say I have an OrderID. I want to have each CartItem as a document inside the OrderID collection. So if the user has 10 items in the cart, there will be 10 documents inside that orderID.

Please help! I've been at this for days now!! Thank you!

1 Answers

Data in the Firestore can be sent only as a Map object. So, you need to convert your CartItem object in the form of Map.

You can do this by creating a method toJson() as follows:

class CartItem {
  String name;
  double singlePrice;
  double quantity;

  CartItem({
    this.name,
    this.singlePrice,
    this.quantity,
  });

  dynamic toJson() => {
    'name': name,
    'singlePrice': singlePrice,
    'quantity': quantity,
  };

  factory CartItem.fromJson(Map<String, dynamic> json) {
    return CartItem(
      name: json['name'],
      singlePrice: json['singlePrice'],
      quantity: json['quantity'],
    );
  }
}

The toJson method will allow you to convert your CartItem object in Map object that can be uploaded to Firebase.

The fromJson method will allow you to convert the data from Firebase back into CartItem object.

For uploading data to Firebase, you can do as follows:

Let's say you have

List<CartItem> _cart = [ CartItem(...), CartItem(...), ...];

Then, you can call the toJson method over each object & upload it to Firebase.

Future<void> _uploadCartToFirebase(List<CartItem> cartList) async {
  for(CartItem cartItem in cartList) {
    await FirebaseFirestore.instance.collection('OrderID').doc()
                                       .set(cartItem.toJson());
  }
}

In case you want cartList back from Firebase:

Future<List<CartItem>> _getCartList() async {
  final querySnapshot = await FirebaseFirestore.instance.
                                collection('OrderID').get();
  List<QueryDocumentSnapshot> docs = querySnapshot.docs;
  final cartList = docs.map((doc) => 
                   CartItem.fromJson(doc.data())).toList();
  return cartList;
}
Related