Skip to content

Instantly share code, notes, and snippets.

@popeyelau
Created January 26, 2024 02:27
Show Gist options
  • Save popeyelau/1153641e06e2b1fa68783bd610ea10b1 to your computer and use it in GitHub Desktop.
Save popeyelau/1153641e06e2b1fa68783bd610ea10b1 to your computer and use it in GitHub Desktop.
main.dart
void main() {
const mockData = {
"code": 200,
"success": true,
"data": {
"name": "Jan",
"age": 20,
}
};
const mockPageData = {
"code": 200,
"success": true,
"data": [
{
"name": "Jan",
"age": 20,
},
{
"name": "John",
"age": 18,
},
]
};
final data = Response<User>.fromJson(mockData, User.decode);
print(data);
final pageData = PagedResponse<User>.fromJson(mockPageData, User.decode);
print(pageData);
}
typedef Decode<T> = T? Function(Map<String, dynamic>);
abstract class BaseResponse {
int code;
bool success;
BaseResponse({required this.code, required this.success});
}
class Response<T> extends BaseResponse {
T? data;
Response({required super.code, required super.success, required this.data});
factory Response.fromJson(Map<String, dynamic> json, Decode<T> decode) {
return Response(
code: json["code"] as int,
success: json["success"] as bool,
data: decode(json["data"]),
);
}
@override
String toString() {
return "code: $code, success: $success, data: $data";
}
}
class PagedResponse<T> extends BaseResponse {
List<T>? data;
PagedResponse(
{required super.code, required super.success, required this.data});
factory PagedResponse.fromJson(Map<String, dynamic> json, Decode<T> decode) {
final _data = json["data"];
if (_data is! List) {
throw RequestError.format(message: "data is not available");
}
return PagedResponse(
code: json["code"] as int,
success: json["success"] as bool,
data: List.from(_data.map((item) => decode(item)).whereType<T>()),
);
}
@override
String toString() {
return "code: $code, success: $success, data: $data";
}
}
class RequestError extends Error {
String message;
RequestError(this.message);
factory RequestError.format({String? message}) {
return RequestError(message ?? "format error");
}
@override
String toString() {
return "error: $message";
}
}
class User {
String name;
int age;
User({required this.name, required this.age});
static User? decode(Map<String, dynamic> json) {
return User(
name: json["name"] as String,
age: json["age"] as int,
);
}
@override
String toString() {
return "name: $name, age: $age";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment