Home > OS >  Flutter Firestore : Add a List of Data to Firestore Document
Flutter Firestore : Add a List of Data to Firestore Document

Time:10-08

I would like to save a List of cart items on Firestore in the Orders collection. I am only able to store the total amount. How can I store the items and quantity in the Cloud Firestore ? or How can I convert the List in a format Firestore can read?

Cart Provider

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });

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

class Cart with ChangeNotifier {
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {..._items};
  }

  int get itemCount {
    return items.values.fold<int>(0, (currentValue, cartItem) {
      return currentValue  = cartItem.quantity;
    });
  }

  double get totalAmount {
    var total = 0.0;
    _items.forEach((key, cartItem) {
      total  = cartItem.price * cartItem.quantity;
    });
    return total;
  }

CartScreen onPressed:

onPressed: () {
                        Provider.of<Orders>(context, listen: false).addOrder(
                          cart.items.values.toList(),
                          cart.totalAmount,
                        );
                        FirebaseFirestore.instance.collection('orders').add({
                          'date': DateTime.now().toString(),
                          'order': '',
                          'total': cart.totalAmount,
                        });
                        cart.clearCart();
                      },

enter image description here

CodePudding user response:

You've to convert the CartItem items to toMap() then pass it to the order field

FirebaseFirestore.instance.collection('orders').add({
                          'date': DateTime.now().toString(),
                          'order': cart.items.values.map((e) => e.toMap()).toList(),
                          'total': cart.totalAmount,
                        });
  • Related