Skip to content

Instantly share code, notes, and snippets.

@blackmann
Created February 3, 2021 00:33
Show Gist options
  • Save blackmann/ed3e931e895083c7fff657efa3cd2666 to your computer and use it in GitHub Desktop.
Save blackmann/ed3e931e895083c7fff657efa3cd2666 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:habanero/models/models.dart';
class CartItem {
final MenuItem item;
int count = 0;
double get total => item.price * count;
CartItem(this.item);
}
class CartProvider extends ChangeNotifier {
final List<CartItem> cartItems = [];
// for ui
CartItem focused;
// debounce
Timer debouncer;
double get itemsTotal {
if (cartItems.length < 1) {
return 0;
}
return cartItems.map((e) => e.total).reduce((a, b) => a + b);
}
void add(MenuItem item) {
final cartItem = cartItems.firstWhere((ci) => ci.item.id == item.id,
orElse: () => CartItem(item));
if (cartItem.count == 0) {
cartItem.count = 1;
cartItems.add(cartItem);
} else {
cartItem.count += 1;
}
notifyListeners();
if (focused != null) {
hideAfter();
}
}
void remove(MenuItem item) {
final cartItem =
cartItems.firstWhere((ci) => ci.item.id == item.id, orElse: () => null);
if (cartItem != null) {
if (cartItem.count == 1) {
cartItems.remove(cartItem);
} else {
cartItem.count -= 1;
}
}
notifyListeners();
if (focused != null) {
hideAfter();
}
}
void removeAll(MenuItem item) {
final cartItem =
cartItems.firstWhere((ci) => ci.item.id == item.id, orElse: () => null);
if (cartItem != null) {
cartItems.remove(cartItem);
notifyListeners();
}
if (focused != null) {
hideAfter();
}
}
void toggle(MenuItem item) {
if (contains(item)) {
removeAll(item);
} else {
add(item);
}
}
void reset() {
cartItems.clear();
notifyListeners();
}
void select(CartItem item) {
focused = item;
notifyListeners();
hideAfter();
}
void hideAfter() {
debouncer?.cancel();
debouncer = Timer(Duration(seconds: 10), () {
focused = null;
notifyListeners();
});
}
bool contains(MenuItem item) =>
cartItems.firstWhere(
(el) => el.item == item,
orElse: () => null,
) !=
null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment