Skip to content

Instantly share code, notes, and snippets.

@verdotte
Last active August 12, 2022 21:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save verdotte/67dec1fb538420d38a8788cbb266a004 to your computer and use it in GitHub Desktop.
Save verdotte/67dec1fb538420d38a8788cbb266a004 to your computer and use it in GitHub Desktop.
import 'dart:collection';
void main() {
Cart cart = Cart();
// add item
cart.addItem(Item(1,'iPhone X', 1, 1000)); // will add the item
cart.addItem(Item(1,'iPhone X', 1, 1000)); // won't add the item since it's already added
cart.addItem(Item(2,'Samsung S20', 2, 2000)); // will add the item
// get item total price
cart.totalPrice
// get list of items
cart.items
// remove one item of id 2
cart.removeOneItem(2);
// remove all items
cart.removeAllItem();
}
class Item {
int id;
String name;
int quantity;
int price;
Item(this.id, this.name, this.quantity, this.price);
}
class Cart {
final List<Item> _items = [];
UnmodifiableListView<Item> get items => UnmodifiableListView(_items);
int get totalPrice => _totalPrice();
int _totalPrice () {
int total = 0;
_items.forEach((Item item) => {
total += item.price * item.quantity
});
return total;
}
bool _checkItem (Item item){
bool isExist = false;
_items.forEach((Item i) => {
if(i.id == item.id){
isExist = true
}
});
return isExist;
}
void addItem(Item item){
if(!_checkItem(item)){
_items.add(item);
} else {
print('item added already');
}
}
void removeOneItem (int id){
_items.removeWhere((Item i) => i.id == id);
}
void removeAllItem () {
_items.clear();
}
}
@ImadBouirmane
Copy link

Thank you for this example

@verdotte
Copy link
Author

You are welcome

@JosephRidge
Copy link

JosephRidge commented Jan 31, 2022

Hi Verdotte thank you for this,
This took me 4days to get i was stuck creating a global list of selecteditems and finalitems, considering i had dynamic items with dynamic textinput fields.. Thank you for this !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment