【Flutter】Dio powerful Dart/Flutter HTTP client

1. Start using

Dio is a powerful Dart/Flutter HTTP client that supports global configuration, interceptors, FormData, request cancellation, file upload/download, timeout, and more.

First, we need to add Dio to the project as a dependency. The latest stable version of Dio can be added using the command line:

$ dart pub add dio

Alternatively, Dio can be manually added to the dependencies section of pubspec.yaml:

dependencies:
 dio: ^5.2.1

If you want to learn more about Flutter and master more tips and best practices, I have good news for you: we have a comprehensive Flutter column -> Flutter Developer 101 Getting Started Booklet waiting for you. There, you will get complete and systematic Flutter learning materials, including detailed code examples and in-depth concept analysis. What's more, our columns are constantly being updated and improved, and the price will gradually increase with the enrichment of content. So, join now and you will get all the content at the best price. Now, let's start learning today!

2. Basic use

Using Dio is very simple. First, we need to import the Dio package and create a Dio instance. We can then use that instance to make HTTP requests. Here is an example of a simple GET request:

import 'package:dio/dio.dart';

final dio = Dio();

void getHttp() async {
    
    
 final response = await dio.get('https://dart.dev');
 print(response);
}

3. Advantages of Dio

Dio has many advantages, including global configuration, interceptors, FormData, request cancellation, file upload/download, timeout, etc. In addition, Dio also supports custom adapters to make it more flexible.

4. Plug-ins

There are many plugins for Dio, including cookie manager, HTTP/2.0 support, native Dio adapter, flexible retry library, HTTPS certificate pinning, Dio to CURL converter, HTTP cache interceptor, and more.

5. Example

1. Initiate a GET request:

import 'package:dio/dio.dart';

final dio = Dio();

void request() async {
    
    
 Response response;
 response = await dio.get('/test?id=12&name=dio');
 print(response.data.toString());
 // The below request is the same as above.
 response = await dio.get(
   '/test',
   queryParameters: {
    
    'id': 12, 'name': 'dio'},
 );
 print(response.data.toString());
}

2. Initiate a POST request:

response = await dio.post('/test', data: {
    
    'id': 12, 'name': 'dio'});

3. Initiate multiple concurrent requests:

response = await Future.wait([dio.post('/info'), dio.get('/token')]);

4. Download the file:

response = await dio.download(
 'https://pub.dev/',
 (await getTemporaryDirectory()).path + 'pub.html',
);

###5. Get the response stream:

final rs = await dio.get(
 url,
 options: Options(responseType: ResponseType.stream), // Set the response type to `stream`.
);
print(rs.data.stream); // Response stream.

6. Use FormData to send data:

final formData = FormData.fromMap({
    
    
 'name': 'dio',
 'date': DateTime.now().toIso8601String(),
});
final response = await dio.post('/info', data: formData);

7. Upload multiple files to the server through FormData:

final formData = FormData.fromMap

{
    
    
 'files': {
    
    
   'file1.txt': MultipartFile.fromFileSync('./text1.txt'),
   'file2.jpg': MultipartFile.fromFileSync('./image.jpg'),
 },
});

final response = await dio.post('/info', data: formData);

8. Use interceptors

Dio allows you to add custom interceptors. Here's an example showing how to add an interceptor that prints the request message before each request:

dio.interceptors.add(
 InterceptorsWrapper(
   onRequest: (options, handler) {
    
    
     print('REQUEST[${
      
      options.method}] => PATH: ${
      
      options.path}');
     return handler.next(options); //continue
   },
 ),
);

6. Conclusion

Dio is a powerful Dart/Flutter HTTP client, which provides many advanced features, such as global configuration, interceptors, FormData, request cancellation, file upload/download, timeout, etc. Whether you're developing complex web applications or building mobile apps, Dio is an option worth considering.

If you are interested in Flutter and want to learn more in-depth, then I would like to recommend you a great resource: our Flutter column -> Flutter Developer 101 Getting Started Booklet . There, you will get complete and systematic Flutter learning materials, including detailed code examples and in-depth concept analysis. For example, do you know how to build a complete app using Flutter? In our column you will find out. What's more, our columns are constantly being updated and improved, and the price will gradually increase with the enrichment of content. So, join now and you will get all the content at the best price. Let's continue exploring in the world of Flutter together! If you want to know more, you can first read our one-stop solution to your needs, Flutter Developer 101 Getting Started Booklet column guide .

Guess you like

Origin blog.csdn.net/diandianxiyu/article/details/131277872