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;
}