DIO IN FLUTTER

Ashmi kattel
4 min readJan 8, 2020

--

Many of us do not have an idea about what Dio in Flutter is! So here I am sharing something about dio which can be helpful for many of us in many cases. Talking about dio , It is a networking library developed by Flutter China. It is powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, ConnectionTimeout etc. Things that dio supports can be done with normal http library which we get in flutter sdk too but its not that easy to learn or understand so dio can be better.

So lets get started with Dio. To get started with Dio first of all you need to add dependency :

dependencies:
dio: ^3.0.8

Then install the package using the command line in your terminal and import it :

For installing the package : flutter pub get Or pub get

Now in your dart code use : import 'package:dio/dio.dart';

  • Now performing a GET request:

Here first of all use a Dio instance then await the response you want to get.

Response response;
Dio dio = new Dio();
response = await dio.get("/test?id=4&name=imhsa");
print(response.data.toString());
  • Performing a POST request:

After getting the request using Dio instance await the request you want to post.

response = await dio.post("/test", data: {"id": 4, "name": "imhsa"});
  • Performing multiple concurrent requests:

Lots of time occurs when you need to call different API in the same instance of time which tends to get confusing some times at that time dio can be used easily to get the responses from different API’s.

response = await Future.wait([dio.post("/info"), dio.get("/token")]);
  • For Downloading a file:

For downloading any sorts of file Dio can be a best decision. It can be done using normal http library which we get in flutter sdk too but its not that easy to learn or understand so dio can be used.

response = await dio.download("https://www.google.com/", "./xx.html","./xx.jpeg","./xx.pdf");
  • Get response stream:

A Stream provides a way to receive a sequence of events. So to get response stream with the flow of your code you need to set responseType to ‘stream’ .

Response<ResponseBody> rs = await Dio().get<ResponseBody>(url,
options: Options(responseType: ResponseType.stream),
// set responseType to `stream`
);
print(rs.data.stream); //response stream
  • Get response with bytes:

To get response in byte you need to set responseType to ‘bytes’ .

Response<List<int>> rs = await Dio().get<List<int>>(url,
options: Options(responseType: ResponseType.bytes),
// set responseType to `bytes`
);
print(rs.data); // List<int>
  • Sending FormData:

To send the FormData use the instance FormData from the map and specify where you want to send the data and await the post.

FormData formData = new FormData.fromMap({
"name": "imhsa",
"age": 22,
});
response = await dio.post("/info", data: formData);
  • Uploading multiple files to server by FormData:

For the time where you need to upload multiple files to server by your formData at that time using MultiPartFile then awaiting it step by step and vice versa can reduce your valuable time.

FormData.fromMap({
"name": "imhsa",
"age": 22,
"file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt"),
"files": [
await MultipartFile.fromFile("./text1.txt", filename: "text1.txt"),
await MultipartFile.fromFile("./text2.txt", filename: "text2.txt"),
]
});
response = await dio.post("/info", data: formData);

It is worth mentioning that the request initiated by HttpClient is still used internally by dio, so the proxy, request authentication, certificate verification, etc. are the same as HttpClient, and we can onHttpClientCreateset it in the callback.

(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
//Setting up a proxy
client.findProxy = (uri) {
return "PROXY 192.168.1.2:8888";
};
//Verification certificate
httpClient.badCertificateCallback=(X509Certificate cert, String host, int port){
if(cert.pem==PEM){
return true;
//If the certificate is consistent, data is allowed to be sent
}
return false;
};
};

Note that it onHttpClientCreatewill be called when the HttpClient needs to be created inside the current dio instance, so configuring HttpClient through this callback will take effect on the entire dio instance. If you want to request a separate proxy or certificate verification policy for an application, you can create a new dio instance.

  • Listening the uploading progress:

To listen the uploading progress of the response after using await in the post request the function onSendProgress can be useful.

response = await dio.post(
"http://www.dtworkroom.com/doris/1/2.0.0/test",
data: {"aa": "bb" * 22},
onSendProgress: (int sent, int total) {
print("$sent $total");
},
);
  • Post binary data by Stream:
// Binary data
List<int> postData = <int>[...];
await dio.post(
url,
data: Stream.fromIterable(postData.map((e) => [e])),
//create a Stream<List<int>>
options: Options(
headers: {
Headers.contentLengthHeader: postData.length,
// set content-length
},
),
);

There are lots of other features provided by dio from dio API like :

baseUrl: It request the base url which normally contains the sub path. Like "https://www.google.com/api/".

connectionTimeout : It contains the timeout in milliseconds for opening url.

receiveTimeout : Whenever the time between two events from response stream is greater then receiveTimeout then the Dio will throw the DioError with DioErrorType.RECEIVE_TIMEOUT .

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

ResponseType :

The response for a request contains the following information.

{
/// Response body. may have been transformed, please refer to [ResponseType].
T data;
/// Response headers.
Headers headers;
/// The corresponding request info.
Options request;
/// Http status code.
int statusCode;
/// Whether redirect
bool isRedirect;
/// redirect info
List<RedirectInfo> redirects ;
/// Returns the final real request uri (maybe redirect).
Uri realUri;
/// Custom field that you can retrieve it later in `then`.
Map<String, dynamic> extra;
}

For each dio instance, We can add one or more interceptors, by which we can intercept requests or responses before they are handled by then or catchError. If you want to resolve and reject the request you can return a Response object or return dio.resolve(data) . If you want to lock/unlock the interceptors you can use lock()/unlock() method.

As you can see Dio contains lots of customization features like adding Cache Retry, Connection time out plus different interceptors, also logs can be included. Dio can be vary useful in the cases where you need the features like offline cache etc. So! This is how Dio works. I hope this article can be useful somehow for all the flutter enthusiast out there.

Please visit https://pub.dev/packages/dio#-readme-tab- for more about Dio Interceptor in Flutter.

Run-able project example : https://github.com/ashmikattel/Dio_demo

--

--