QueenFruits/Mobile Commerce/lib/features/cart/presentation/controllers/cart_controller.dart

72 lines
1.8 KiB
Dart

import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/features/cart/domain/entities/cart.dart';
import 'package:niogu_ecommerce_v1/features/cart/presentation/providers/cart_provider.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/entities/home.dart';
class CartItemsController extends StateNotifier<Map<String, CartItem>> {
CartItemsController() : super({});
void hydrate(List<CartItem> cartItems) {
state = {
...state,
for (final cartItem in cartItems)
"${cartItem.outletId}-${cartItem.id}": cartItem,
};
}
void increment(CartItem item, {int? quantity}) {
final key = "${item.outletId}-${item.id}";
final cartItem = state[key];
if (cartItem == null) {
state = {...state, key: item};
} else {
state = {
...state,
key: item.copyWith(quantity: cartItem.quantity + (quantity ?? 1)),
};
}
}
void decrement(String outletId, String id) {
final key = "$outletId-$id";
final cartItem = state[key];
if (cartItem == null) return;
if (cartItem.quantity <= 1) {
state = {...state}..remove(key);
} else {
state = {
...state,
key: cartItem.copyWith(quantity: cartItem.quantity - 1),
};
}
}
void clear() {
state = {};
}
}
class ProductBestSellerController
extends AutoDisposeAsyncNotifier<List<ProductItem>> {
@override
FutureOr<List<ProductItem>> build() => _fetchProductBestSellers();
Future<List<ProductItem>> _fetchProductBestSellers() async {
final cartRepository = ref.read(cartRepositoryProvider);
return await cartRepository.fetchProductBestSellers();
}
Future<void> refresh() async {
ref.invalidateSelf();
await future;
}
}