Network Request with GetConnect in flutter

tayo olakunle
4 min readJun 23, 2021
https://unsplash.com/photos/rhNff6hB41s

This article is intended for those who use Getx package to manage their state or route, but use other packages to handle network calls like Dio or Http.

Getx is arguably the easiest to use lightweight state management package for flutter and it is widely accepted by the flutter community being the most liked flutter package.
Today we would explore another part of the Getx package aside from the widely known route and state management, this article will focus on networking with GetConnect.

The documentation is out of the box for many to understand but still, there are better ways to go about solutions.
Being a big fan of Dio package, I started to explore everything Dio can do if GetConnect can do the same, and yes I found some interesting stuff I can show off.

Talk is cheap show me the code.

Want to read this story later? Save it in Journal.

First let’s create a BaseService class where we would do the basic configuration of our GetConnect class.

class BaseService extends GetConnect {
@override
void onInit() {
// add your local storage here to load for every request
var token = LocalStorage.readToken();
//1.base_url
httpClient.baseUrl = "http://base_url here";
//2.
httpClient.defaultContentType = "application/json";
httpClient.timeout = Duration(seconds: 8);
httpClient.addResponseModifier((request, response) async {
print(response.body);
});
httpClient.addRequestModifier((request) async {
// add request here
return request;
});
var headers = {'Authorization': "Bearer $token"};
httpClient.addAuthenticator((request) async {
request.headers.addAll(headers);
return request;
});

super.onInit();
}
}

Our BaseService class extends GetConnect giving the base class access to all its method declarations.
The GetConnect has an onInit method that needs to be overridden. Inside the onInit method we do all our base setup, these are things that are likely constant throughout the application, for example;

1. The base url: this is where you set the base url of your endpoint so you don’t have to call it over and over again.

2. The headers: this is where you add the content type you are about sending to the server, most time they are application/json except in rare cases.

3. On Request Modifier: this is an interceptor that intercepts your request, for example you want to print the url on every request it intercepts the request to perform its specified action when making the request.

4. Authentication: this is where you specify your token headers like basic auth or oAuth or the popular bearer token.

5. On response modifier: this is an interceptor that intercepts when the request is completed.

And that’s all we need to do for the configuration.What we need next is to use the base service throughout the whole application. Next, create another class called the PersonService and let it extend BaseService this time.

class PersonService extends BaseService {
/// add your service code here
}

Now PersonService has all the methods of BaseService including GetConnect we extended in BaseService class.
Now to perform our network request, all we need to do is this:

/// for get requests.Future<ResponseModel> getPersonData() async {
var res = await get("person_url");
print(res);
}
/// for post requests.Future<ResponseModel> postPersonData(dynamic body) async {
var res = await post("person_url", body);
print(res);
}
/// for put requests.Future<ResponseModel> putPersonData(dynamic body) async {
var res = await put("person_url", body);
print(res);
}
/// for delete requests.Future<ResponseModel> deletePersonData() async {
var res = await delete("person_url");
print(res);
}

See how simple it is to pass the url? Just pass the remaining part of the url, and GetConnect connects the base url with the url automatically for you leaving you the stress of knowing how they are linked together.

GetConnect also has other nice method that are worth exploring depending on your use case

/// for adding a trusted certificate to the request
@override
set trustedCertificates(List<TrustedCertificate> _trustedCertificates) {
// TODO: implement trustedCertificates
super.trustedCertificates = _trustedCertificates;
}
/// for making socket request
@override
GetSocket socket(String url, {Duration ping = const Duration(seconds: 5)}) {
// TODO: implement socket
return super.socket(url, ping);
}
/// for setting up GraphQl with getConnect
@override
Future<GraphQLResponse<T>> mutation<T>(String mutation, {String url, Map<String, dynamic> variables, Map<String, String> headers}) {
// TODO: implement mutation
return super.mutation(mutation, url, variables, headers);
}

Also, to enable us have a base error response class that handles errors for us, Getx doesn’t have any out of the box but hoping they would consider that in the nearest future while but here is what you can do to handle your errors yourself.

Create a new method called error handler

dynamic errorHandler(Response response) {
print(response.toString());
switch (response.statusCode) {
case 200:
case 201:
case 202:
var responseJson = response.body.toString();
return responseJson;
case 500:
throw "Server Error pls retry later";
case 403:
throw 'Error occurred pls check internet and retry.';
case 500:
default:
throw 'Error occurred retry';
}
}

Now to connect our error handler to our request go into PersonService class, and add a try catch to your request to catch the error.

Future<ResponseModel> postPersonData(dynamic body) async {
var res;
try {
res = await post("url", body);
return ResponseModel.fromJson(res.body);
} catch (e) {
errorHandler(res);
}
}

And that’s all we need to do to connect our app to the server using GetConnect without any added package like Http or Dio or retrofit and the likes.

I hope this was helpful, if you have any questions please drop on the comment section I would be happy to answer

Here is a link to the Git repo thats shows how it works

Happy Fluttering 💙

Enjoyed this post? Subscribe to the Machine Learnings newsletter for an easy understanding of AI advances shaping our world.

--

--