Created
January 26, 2024 02:27
-
-
Save popeyelau/1153641e06e2b1fa68783bd610ea10b1 to your computer and use it in GitHub Desktop.
main.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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