Tuesday, June 16, 2020

Flutter - Dio client to create Http Request

Today, all the mobile and web applications depend on back-end API's that we can consume with the help of Http client. Flutter framework offers Http package that works great when we need to do basic stuff. We have explained GET and POST request with http here Flutter - GET and POST http requests.

When you start working on a big application and we need to do something more advanced task. Your application will face lots of problems with network error handling. In that case, we need something big and advance connection library which has extra features like interceptors, logs, cache, etc, that will be helpful in many tasks like adding the token authentication for each request and logging requests.

In this post, we're going to learn all methods, features, and error handling of the Dio Http client to accomplish our goal. The Dio client is a powerful Http client for Dart or Flutter application which supports Interceptors, Global configuration, Request Cancellation, FormData, File downloading, ConnectionTimeout, etc that will be helpful in many tasks such as adding token authentication for each request and logging requests.



the Dio Http Client package

To use Dio Http client in Flutter application we have to install it. So, add it in the dependencies section of the pubspec.yaml.

dependencies:
dio: ^3.0.9

After that, run flutter packages to get it.

GET request

To use methods of Dio Http client, we have to create instance of the Dio client. After that can call all methods of Dio. As you can see, we have create instance of Dio and calling GET request:
developerlibs() async {
var dio = Dio();
Response response = await dio.get('https://developerlibs.com');
print(response.data);
}

the response instance will catch data of the GET request API.


POST request

The instance of Dio provide POST method where we can pass param in JOSN format. As you can see, we have passed name of API /developerlibs and data will carry params:
developerlibs() async {
var dio = Dio();
Response response = await dio.post("/developerlibs", data: {"id": 4, "name": "dev"});
print(response.data);
}


Multiple concurrent requests

Sometimes, we have to call more than one API's at the same time and, at the same time manage the response of all the API is very complex. The Dio can call and manage responses from different APIs very easily as shown below:
developerlibs() async {
var dio = Dio();
Response response = await Future.wait([dio.post("/info"), dio.get("/token")]);
print(response.data);
}


Download a file from server.

To download a file from server, Dio provide download method. In this method, we have to pass complete path of file.
developerlibs() async {
var dio = Dio();
Response response = await dio.download("https://www.developerlibs.com/pdf", "./xx.html","./xx.jpeg","./xx.pdf");
print(response.data);
}



Get response stream

With the help of stream response, we can receive a sequence of events. To get response stream with Dio client, we need to set responseType stream.
developerlibs() async {
var dio = Dio();
Response<ResponseBody> rs = await dio.get<ResponseBody>("www.developerlibs.com",
options: Options(responseType: ResponseType.stream),
);
print(rs.data.stream);
}




Get response with bytes

To get response in byte, we have to set responseType bytes as explain above for stream.
developerlibs() async {
var dio = Dio();
Response<List<int>> rs = await dio.get<List<int>>(url,
options: Options(responseType: ResponseType.bytes),
);
print(rs.data);
}


Sending FormData:

To send the form data, we can use instance of FormData and pass mapping values of keys  and specify where you want to send the data.
developerlibs() async {
var dio = Dio();
FormData formData = new FormData.fromMap({
"name": "imhsa",
"age": 22,
});
Response response = await dio.post("/info", data: formData);
print(response.data);
}


Uploading multiple files to server by FormData:

The Dio client provide form data to upload single or multiple file to server in MultiPartFile.  Along with file, we can pass required param with same request:
developerlibs() async {
var dio = Dio();
var
formData = FormData.fromMap({
"name": "developerlibs",
"age": 5,
"file": await MultipartFile.fromFile("./
developerlibs.txt",filename: "developerlibs.txt"),
"files": [
await MultipartFile.fromFile("./
developerlibs.txt", filename: "developerlibs.txt"),
await MultipartFile.fromFile("./
developerlibs.txt", filename: "developerlibs.txt"),
]
});
Response response = await dio.post("/resource", data: formData);
}


set proxy

The dio provide simple steps to set proxy:
import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
// config the http client
client.findProxy = (uri) {
//proxy all request to localhost:8888
return "PROXY localhost:8888";
};
// you can also create a new HttpClient to dio
// return new HttpClient();
};





Listening the uploading progress

Some time, we need to listen the uploading progress of the response after using await in the post request. The dio provide onSendProgress function to listen the uploading progress .

developerlibs() async {
var dio = Dio();
Response response = await dio.post(
"http://www.developerlibs.com/resource/1/2.0.0/test",
data: {"aa": "bb" * 22},
onSendProgress: (int sent, int total) {
print("$sent $total");
},
);
}


Creating an instance and set default configs

You can create instance of Dio with an optional BaseOptions object or inject all param into Dio instance:
Dio dio = new Dio(); // with default Options

// Set default configs
dio.options.baseUrl = "https://www.xx.com/api";
dio.options.connectTimeout = 5000; //5s
dio.options.receiveTimeout = 3000;

// or new Dio with a BaseOptions instance.
BaseOptions options = new BaseOptions(
baseUrl: "https://www.xx.com/api",
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);

As you can see, Dio provides lots of features like adding Cache Retry, Connection time out plus different interceptors, request and response logs and vary useful for offline cache etc. I hope this post can be useful somehow for all the Flutter enthusiast out there.

Please visit Dio http cient for more update and information.

Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...