REST API Calls in Flutter using Dio

When you are building a mobile application, there is a high chance that it would require some sort of internet connectivity for data fetching and other features. In this article, we would present how you can make Flutter API Calls.

Packages

The package we would be using is called dio. You can get the package by adding it in your pubsec.yaml file just like shown here:

dependencies:
  dio: ^4.0.0

Get Call

For a normal Get call, you may just call it as:

Future<dynamic> myGetCall() async {
await Dio()
.get(\'http://dummy.restapiexample.com/api/v1/employees\')
.then((value){
return value;
})
.catchError((err){
return err;
});
}

This would make a call to get the data from the provided API (currently from Rest API Example). Once it gets the data, it would turn to the then part of the method and return the value otherwise it would go to catchError part of the method and return the error.

Post Call

Now when making a post call, there is a chance that you may be passing some parameters. For such, we would call the POST method and pass query parameters as shown below:

Future<dynamic> myPostCall(Map<String, String> queryParameters) async {
await Dio()
.post(\'http://dummy.restapiexample.com/api/v1/create\', queryParameters: queryParameters)
.then((value){
return value;
})
.catchError((err){
return err;
});
}

Headers in REST API

What if you would like to pass some header information, such as user\’s language, Id, or perhaps some form of token. For that, we would be making an object of the options class where we would add our headers:

final BaseOptions options = BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000
);

options.headers.addAll({
\"lang\": lang,
\"userId\": userId
}

Once we have set the option values, we would make our POST and GET calls by just passing the Option object in the constructor of Dio.

Future<dynamic> myGetCall() async {
await Dio(options)
.get(\'http://dummy.restapiexample.com/api/v1/employees\')
.then((value){
return value;
})
.catchError((err){
return err;
});
}
Future<dynamic> myPostCall(Map<String, String> queryParameters) async {
await Dio(options)
.post(\'http://dummy.restapiexample.com/api/v1/create\', queryParameters: queryParameters)
.then((value){
return value;
})
.catchError((err){
return err;
});
}


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *