Working with APIs in flutter using Dio Package

All of us have heard about http package when we consider connecting to APIs in our flutter App but many of us don’t know about Dio. Dio is powerfull Http client for Dart developed by flutter Chinese community which I found more suitable and comfortable working with APIs. I was developing a Food Delivery App where I was dealing with APIs and using http package for that. http package works fine in beginning but when I was sending order details to server with list of products, it crashes. I was struggling to remove the error as console was showing a type casting error. After a lot of struggle when I was unable to remove that error, I switched my code to Dio package and amazed to see everything works fine with the same code. I just realized the issue was not on my side, it was some internal error of http package which later confirmed when my friend told me that he was encountered with same error. After that I just decided to use Dio as http client and here I am writing the detail on how to use it.
Lets just start but adding the dependency to your pubspec.yaml file:
dependencies:
dio: latest_version
Then install the package using command line or by pressing the pub get icon in top right corner of your file.
For installing: $flutter pub get or pub get
Now import the Dio package in your dart file where you will supposed to do API calling.
import ‘package:dio/dio.dart’;
- Now Start with calling GET request:
First of all create Dio instance by which we will call get method of it.
Dio dio = Dio();
var url = 'your-url';
//queryParameters will the parameter required by your API.
//In my case I had to send the headers also, which we can send using //Option parameter in request. Here are my headers Map:
var header = {'Content-type': 'application/json; charset=utf-8'};
var responce = await dio.get(url,
options: Options(
headers: headers
),);
if(responce.statusCode == 200){
print(responce.data.toString);
}
We have to await the execution as dio methods retuns Future<response> and execution needs to be stopped to get response before moving to next step.
Here Response can be of any type provided by the server. Its usually returns this data in Json which we need to convert into our model object for being able to wrap it on our user interface(UI).
- Now Performing a POST request:
var url = 'api_url';
//data will be the object which we want to send.
//In my case I am sending a product to insert.
Product product = Product(name:'Pizza', price: 130.00);
var header = {'Content-type': 'application/json; charset=utf-8'};
var responce = await dio.post(url,data: product.toJson,
options: Options(
headers: headers
),);
if(responce.statusCode == 200){
// Status is the message receiving in responce saying product
//inserted successfully.
print(responce.data['Status']);
}
- Downloading a File
We can add the functionality in our app which let our users download a file from our server using dio instance and its super easy.
response = await dio.download('file-url', './xx.html', './xx.jpeg','./xx.pdf');
here the file url will be the address of the API/URL where our file is located on internet. After that these were the supported types which will be downloaded.
- Sending FormData to API
Sending formData is similar to post request discussed above.
var formData = FormData.fromMap({
'name': 'wendux',
'age': 25,
});
var response = await dio.post('api url', data: formData);
data parameter here receive formData instead of JSON Object we send earlier in post request.
For sending multipart request and Images to server see my article “Sending Images to server in flutter ”.
- Listening the uploading progress:
While sending data to server Dio provide us the ability to track our progress. It returns the progress is recieved in Integar along with total value to see how much data have been sent out of total.
response = await dio.post(
“your-url",
data: objectData,
onSendProgress: (int sent, int total) {
print(“$sent $total”);
},
);
That was some basic functionalities/tasks we need to perform every time we communicate to server through our App. Hope you understand well and if you have any queries just let me know in comments.
Thanks for your cooperation.