From a472156d2288c374625291d70528113e14e7358c Mon Sep 17 00:00:00 2001 From: Sambo Chea Date: Fri, 28 Oct 2022 10:33:56 +0700 Subject: [PATCH] Add base model --- example/my_cart_example.dart | 34 ++++++++++++++++++++++++---------- lib/model.dart | 3 +++ lib/src/model/base.dart | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 lib/model.dart create mode 100644 lib/src/model/base.dart diff --git a/example/my_cart_example.dart b/example/my_cart_example.dart index 1f78c4b..81ee6b7 100644 --- a/example/my_cart_example.dart +++ b/example/my_cart_example.dart @@ -1,16 +1,14 @@ -import 'dart:convert'; - -import 'package:cubetiq/interfaces.dart'; +import 'package:cubetiq/model.dart'; void main(List args) { MyCart.addCart( - Cart(1, 'Apple', 1), + Cart(id: 1, name: 'Apple', qty: 1), ); MyCart.show(); MyCart.addCart( - Cart(1, 'Apple', 2), + Cart(id: 1, name: 'Apple', qty: 2), ); MyCart.show(); @@ -24,15 +22,24 @@ void main(List args) { MyCart.show(); } -class Cart implements ToJson { +class Cart extends BaseModel { final int id; - final String name; + final String? name; double qty; - Cart(this.id, this.name, this.qty); + Cart({this.id = -1, this.name, this.qty = 0}); @override - Map toJson() { + Cart fromMap(Map map) { + return Cart( + id: map['id'], + name: map['name'], + qty: map['qty'], + ); + } + + @override + Map toMap() { return { 'id': id, 'name': name, @@ -71,7 +78,14 @@ class MyCart { } static void show() { - var data = carts.map((key, value) => MapEntry(key, jsonEncode(value))); + var data = carts.map((key, value) => MapEntry(key, value)); + var json = data.map((key, value) => MapEntry(key, value.toJson())); + var model = json.map((key, value) => MapEntry(key, Cart().fromJson(value))); + print('================ Map ================='); print('$data'); + print('================ Json ================='); + print('$json'); + print('================ Model ================='); + print('$model'); } } diff --git a/lib/model.dart b/lib/model.dart new file mode 100644 index 0000000..ae1858d --- /dev/null +++ b/lib/model.dart @@ -0,0 +1,3 @@ +library model; + +export 'src/model/base.dart'; \ No newline at end of file diff --git a/lib/src/model/base.dart b/lib/src/model/base.dart new file mode 100644 index 0000000..e965b88 --- /dev/null +++ b/lib/src/model/base.dart @@ -0,0 +1,33 @@ +import 'dart:convert'; + +abstract class BaseModel { + BaseModel(); + + Map toMap(); + + T fromMap(Map map); + + T fromJson(String json) { + return fromMap(decode(json)); + } + + @override + String toString() { + return toMap().toString(); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is BaseModel && other.toMap() == toMap(); + } + + @override + int get hashCode => toMap().hashCode; + + String toJson() => encode(toMap()); + + dynamic decode(String json) => jsonDecode(json); + String encode(dynamic json) => jsonEncode(json); +}