From f555d68a2963dc5d39706785431ad39e357c807a Mon Sep 17 00:00:00 2001 From: Sambo Chea Date: Wed, 9 Jun 2021 14:33:18 +0700 Subject: [PATCH] Task: Add my cart code example to explain a local cart mutable --- example/my_cart_example.dart | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 example/my_cart_example.dart diff --git a/example/my_cart_example.dart b/example/my_cart_example.dart new file mode 100644 index 0000000..1f78c4b --- /dev/null +++ b/example/my_cart_example.dart @@ -0,0 +1,77 @@ +import 'dart:convert'; + +import 'package:cubetiq/interfaces.dart'; + +void main(List args) { + MyCart.addCart( + Cart(1, 'Apple', 1), + ); + + MyCart.show(); + + MyCart.addCart( + Cart(1, 'Apple', 2), + ); + + MyCart.show(); + + MyCart.inc(1, qty: 2); + + MyCart.show(); + + MyCart.dec(1, qty: 4); + + MyCart.show(); +} + +class Cart implements ToJson { + final int id; + final String name; + double qty; + + Cart(this.id, this.name, this.qty); + + @override + Map toJson() { + return { + 'id': id, + 'name': name, + 'qty': qty, + }; + } +} + +class MyCart { + static final Map carts = {}; + + static void inc(int id, {double qty = 1}) { + if (carts.containsKey(id)) { + carts[id]!.qty += qty; + } + } + + static void dec(int id, {double qty = 1}) { + if (carts.containsKey(id)) { + carts[id]!.qty -= qty; + } + } + + static void addCart(Cart cart) { + if (carts.containsKey(cart.id)) { + carts[cart.id]!.qty += cart.qty; + } else { + carts[cart.id] = cart; + } + } + + static void removeCart(Cart cart) { + if (carts.containsKey(cart.id)) { + carts.remove(cart.id); + } + } + + static void show() { + var data = carts.map((key, value) => MapEntry(key, jsonEncode(value))); + print('$data'); + } +}