Skip to content

Instantly share code, notes, and snippets.

@Kaival-Patel
Created January 27, 2023 09:41
Show Gist options
  • Select an option

  • Save Kaival-Patel/6e1219212e9711d14a8bae2250b8695c to your computer and use it in GitHub Desktop.

Select an option

Save Kaival-Patel/6e1219212e9711d14a8bae2250b8695c to your computer and use it in GitHub Desktop.
Api Generic Response Model
import 'dart:convert';
String apiResponseToJson(ApiResponse data) => json.encode(data.toJson());
class ApiResponse<T> {
ApiResponse({
this.s = 0,
this.m = "",
this.r,
this.c=0,
});
int s;
String m;
T? r;
int c;
factory ApiResponse.fromBaseJson(Map<String, dynamic> json) => ApiResponse<T>(
s: json["s"] == null ? null : json["s"],
m: json["m"] == null ? null : json["m"],
);
bool get isValid => s == 1;
factory ApiResponse.fromStringJson(Map<String, dynamic> json,Function(String) create) => ApiResponse<T>(
s: json["s"] == null ? null : json["s"],
m: json["m"] == null ? null : json["m"],
c: json["c"] == null ? 0 : int.tryParse(json["c"].toString())??0,
r: json["r"] == null ? null : create(json["r"].toString()),
);
factory ApiResponse.fromMapJson(
Map<String, dynamic> json, Function(Map<String, dynamic>) create) =>
ApiResponse<T>(
s: json["s"] == null ? null : json["s"],
c: json["c"] == null ? 0 : int.tryParse(json["c"].toString())??0,
m: json["m"] == null ? null : json["m"],
r: json["r"] == null ? null : create(json["r"]),
);
//FOR GETTING LIST OF MAPS
factory ApiResponse.fromListJson(
Map<String, dynamic> json, Function(List<dynamic>) create) =>
ApiResponse<T>(
s: json["s"] == null ? null : json["s"],
c: json["c"] == null ? 0 : int.tryParse(json["c"].toString())??0,
m: json["m"] == null ? null : json["m"],
r: json["r"] == null ? null : create(json["r"]),
);
//FOR GETTING INTS
factory ApiResponse.fromIntJson(
Map<String, dynamic> json, Function(int) create) =>
ApiResponse<T>(
s: json["s"] == null ? null : json["s"],
m: json["m"] == null ? null : json["m"],
c: json["c"] == null ? 0 : int.tryParse(json["c"].toString())??0,
r: json["r"] == null ? null : create(json["r"]),
);
//FOR GETTING INTS
factory ApiResponse.fromIntWithJson(
Map<String, dynamic> json, Function(Map<String,dynamic>) create) =>
ApiResponse(
s: json["s"] == null ? null : json["s"],
m: json["m"] == null ? null : json["m"],
c: json["c"] == null ? 0 : int.tryParse(json["c"].toString())??0,
r: json["r"] == null ? null : create(json),
);
//Factoruuu method for returning error models directly to the view
factory ApiResponse.fromError(
{String errorMessage = "Something went wrong"}) =>
ApiResponse<T>(
s: 0,
m: errorMessage,
);
Map<String, dynamic> toJson() => {
"s": s,
"m": m,
"r": r,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment