I have created Shopping cart for ecommerce app. I am able to add new item to cart with quantity 1, but other condition of If where item is already in cart, quantity is not increasing by + 1. I am not getting any error as well in console.
Also, How do i save this in local database. whenever i refresh app, cart items becomes 0.
class CartItemStored with ChangeNotifier {
Map<String, Product> _newitemList= {};
Map<String, Product> get newItemList{
return{..._newitemList};
}
List<Product> _list =[];
List<Product> get list{
return[..._list];
}
int get itemListCount {
return newItemList.length;
}
double get totalAmount {
var total = 0.0;
_newitemList.forEach((key, cartItem) {
total += cartItem.productListPrice * cartItem.quantity;
});
return total;
}
void addtoCart(
int productId,
String productName,
int productListPrice,
int productSalePrice,
String productSku,
int quantity,
) {
if (_newitemList.containsKey(productId)){
_newitemList.update(productId.toString(), (existingCartItem) => Product(
productId: productId,
productName: productName,
productListPrice: productListPrice,
productSalePrice: productSalePrice,
productSku: productSku,
quantity: quantity + 1,
));
} else{
_newitemList.putIfAbsent(productId.toString(), ()=> Product(
productId: productId,
productName: productName,
productListPrice: productListPrice,
productSalePrice: productSalePrice,
productSku: productSku,
quantity: 1,
));
}notifyListeners();
DBHelper.insert('cart', {
'productId': productId,
'productName': productName,
'productListPrice': productListPrice,
'productSalePrice': productSalePrice,
'productSku': productSku,
'quantity': quantity,
});
}
Future<void> fetchAndSetCart() async {
final dataList = await DBHelper.getCartData('cart');
_newitemList = dataList.map((itemList) => Product(
productId: itemList['productId'],
productName: itemList['productName'],
productSalePrice: itemList['productSalePrice'],
productListPrice: itemList['productListPrice'],
productSku: itemList['productSku'],
quantity: itemList['quantity'],
)) as Map<String, Product>;
notifyListeners();
}
}
class DBHelper {
static Future<Database> database() async {
final dbPath = await sql.getDatabasesPath();
return sql.openDatabase(path.join(dbPath, 'cart.db'),
onCreate: (db, version) {
db.execute(
'CREATE TABLE cart(productId TEXT, productName TEXT,productListPrice TEXT,productSalePrice TEXT,productSku TEXT,quantity TEXT)');
}, version: 1);
}
static Future<void> insert(String table, Map<String, Object> data) async {
final db = await DBHelper.database();
db.insert(table, data, conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
static Future<List<Map<String, dynamic>>> getCartData(String table) async {
final db = await DBHelper.database();
return db.query(table);
}
}