Add models and sdk services example

This commit is contained in:
2022-10-28 10:10:46 +07:00
parent 82de95b4b7
commit d0f3debf2e
18 changed files with 598 additions and 85 deletions

View File

@@ -1,6 +0,0 @@
class Category {
int id;
String name;
Category(this.id, this.name);
}

View File

@@ -1,20 +0,0 @@
class Product {
int id;
String name;
double price;
Product(this.id, this.name, this.price);
static Product fromJson(dynamic json) => Product(
json['id'],
json['name'],
json['price'],
);
}
class ProductRequest {
String name;
double price;
ProductRequest(this.name, this.price);
}

31
lib/sdk/models/base.dart Normal file
View File

@@ -0,0 +1,31 @@
import 'dart:convert';
abstract class BaseModel<T> {
BaseModel();
Map<String, dynamic> toMap();
T fromMap(Map<String, dynamic> map);
T fromJson(String 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);
}

View File

@@ -0,0 +1,34 @@
import 'package:sample_sdk/sdk/models/base.dart';
class Category extends BaseModel<Category> {
int? id;
String? name;
Category? parent;
Category({this.id, this.name, this.parent});
@override
Category fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
parent = Category().fromJson(map['parent']);
return this;
}
@override
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'parent': parent?.toMap(),
};
}
@override
Category fromJson(String json) {
return fromMap(decode(json));
}
static Category fromJsonString(dynamic json) => Category().fromJson(json);
}

View File

@@ -0,0 +1,38 @@
import 'package:sample_sdk/sdk/models/base.dart';
import 'package:sample_sdk/sdk/models/category.dart';
class Product extends BaseModel<Product> {
int? id;
String? name;
double? price;
Category? category;
Product({this.id, this.name, this.price, this.category});
@override
Product fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
price = map['price'];
category = Category().fromJson(map['category']);
return this;
}
@override
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'price': price,
'category': category?.toMap(),
};
}
@override
Product fromJson(String json) {
return fromMap(decode(json));
}
static Product fromJsonString(String json) => Product().fromJson(json);
}