When building mobile applications, network operations are essential, such as making API requests or uploading files. Flutter Dio is a powerful Flutter package that simplifies network operations - it offers features such as cancelling requests, handling errors, and intercepting requests and responses.
To use Flutter Dio, add the package to your pubspec.yaml
file:
dependencies:
dio: ^4.0.0
Then, run flutter pub get
in your terminal.
Next, import the package in your Dart file:
import 'package:dio/dio.dart';
To perform network requests using Flutter Dio, create an instance of the Dio
class and use its methods.
To make a GET
request, for example, use the get
method:
final response = await Dio().get('https://jsonplaceholder.typicode.com/posts');
To make a POST
request, use the post
method:
final response = await Dio().post('https://jsonplaceholder.typicode.com/posts', data: {
"title": "foo",
"body": "bar",
"userId": 1
});
With Dio, you can handle network errors gracefully. When making a request that could fail, use the try-catch
statement to handle potential errors.
try {
final response = await Dio().get('https://jsonplaceholder.typicode.com/404');
} on DioError catch (e) {
print(e.message);
print(e.response.data);
print(e.response.headers);
print(e.response.requestOptions);
}
In the catch
block, you have access to the error message, response data, headers and request options. You can handle the error accordingly in your application.
Dio makes it easy to cancel requests if they are no longer needed, such as when a user navigates away from a screen or cancels an operation.
To cancel a request, first create a CancelToken
:
final cancelToken = new CancelToken();
Then, when making the request, pass the token as a parameter:
final response = await Dio().get('https://jsonplaceholder.typicode.com/posts', cancelToken: cancelToken);
To cancel the request at any time, call the cancel()
method:
cancelToken.cancel('cancelled');
Dio allows you to intercept and modify requests and responses. To do so, create an instance of the InterceptorsWrapper
class and add it to your Dio
instance.
For example, to add an authorization header to all requests, use the onRequest
method:
final dio = Dio();
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// Add an authorization header
options.headers['Authorization'] = 'Bearer token';
return handler.next(options);
},
));
You can also use the onResponse
and onError
methods to modify response data and handle errors, respectively.
Flutter Dio makes network operations easy by simplifying tasks such as making HTTP requests, handling errors and intercepting requests and responses. It's a powerful package that can help you build robust mobile applications.