If you like Either<L, R> datatype from the dartz package, and tired of writting boilerplates for consuming REST Api in Either<L, R> This Package is the solution for you.
MinRest acts as a REST Client and returns data as your DataModel or Entity whichever object you want.
- Making all kind of
httprequest - It returns your
DataModelby making ahttprequest and returnsEither<YourModel, Error>
You need to Initialize the MinRest singleton with the base url
Let's do it int the main.dart file
void main() {
WidgetsFlutterBinding.ensureInitialized();
...
MinRest.init("https://jsonplaceholder.typicode.com/todos/1");
...
runApp(Main());
}- Your own DataModel class
Let's say we have a
DataModelnamedUserModel
class UserModel {
final String name;
final String email;
UserModel({required this.name, required this.email});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'name': name,
'email': email,
};
}
}- Make the API call and get
Either<MinRestError, UserModel>
final userOrError = await MinRest().getErrorOr<UserModel>(
"/path_to_user_data",
(json) => UserModel.fromJson(json),
);Note that
MinRestErroris the default error objectMinRestwill return in theLeftside ofEither
- Fold and using the data
Now you can use
userOrErrorjust like anyEither<L, R>object. Let'sfolduserOrError and print thenameandemailof the user if the request and response is successful. (status code from 200 to 199)- or print the
errorstatus code andmessageof the request is failed
userOrError.fold(
(error) => print("Error: ${error.code} - ${error.message}"),
(user) => print("User: ${user.name} - ${user.email}"),
);How to use MinRest
final userOrError = await MinRest().getErrorOr<UserModel>(
"/path_to_user_data",
(json) => UserModel.fromJson(json),
token: token.accessToken,
);final postData = await MinRest().postErrorOr<UserModel>(
"/path_to_user_data",
userModel.toJson(),
(json) => UserModel.fromJson(json),
token: token.accessToken,
);final patchData = MinRest().patchErrorOr<UserModel>(
uri: "/auth/update-profile",
data: userModel.toJson(),
deSerializer: (json) => UserModel.fromJson(json),
errorDeserializer: (json) => AppError.fromJson(json),
token: token.accessToken,
);final deleteData = MinRest().deleteErrorOr(
uri: "/auth/delete-account",
deSerializer: (json) => RestResponseNoEntity.fromJson(json),
errorDeserializer: (json) => AppError.fromJson(json),
token: token.accessToken,
)Here AppError is your custom ErrorModel, (Later this will be implemented in other methods as well, Get and Post methods now returns
MinRestErroronly)