1. Import the dio package
Currently, the latest version of the dio library is 3.0.1. Just like using other three-party libraries, the configuration file is also required for using the dio library in Flutter.
dependencies: flutter: sdk: flutter dio: ^3.0.10
2. Import and create an instance
After the dio package is successfully introduced, you can create a dio instance. One instance can initiate multiple requests. If there is only one data source in the APP, you can consider creating the dio instance into a singleton mode, which can save system resources and reduce unnecessary overhead.
// import 'package:dio/'; var dio = Dio();
3. Basic configuration
Before starting to use the instance, you need to make some basic settings for the instance. Since each person’s project needs are different, I will only write a few simple configurations for my own small project here:
//Unified configuration of dio = "";//baseUrl = 5000;//Timeout time = 3000;//Maximum time to receive data = ;//Data format
It can also be configured by creating an option:
BaseOptions options = BaseOptions(); = ""; = 5000; = 3000; = ; = options;
The above introduces two ways to configure dio instances, and uniformly configures several simple attributes such as baseUrl, link timeout, maximum data time, and data type of the received packet. There are some other configurations in dio, you can refer to dio's homepage/flutterchin…
4. Use examples
How to use the dio instance after the configuration is completed? Let’s demonstrate by requesting to play the banner image on the Android homepage: The basic steps are: The first step is to request data first, the second step is to convert the requested json data into a model, and the third step is to render the model data into a carousel image:
child: FutureBuilder( future: ("/banner/json"), builder: (context, snapshot) { if ( == ) { Response response = ; Map bannerMap = (()); var banner = (bannerMap); if () { (msg: ()); } else { return _getSwiper(); // (msg: [0].title); } } return Center( child: CircularProgressIndicator(), ); }, ), //Create a carousel diagram based on the data returned by the interface Swiper _getSwiper(List<Datum> data) { (); for (var i = 0; i < ; i++) { var image = ( data[i].imagePath, fit: , ); (image); } return Swiper( itemWidth: , itemHeight: 200, itemCount: , itemBuilder: (BuildContext context, int index) { return imgs[index]; }, autoplay: true, pagination: new SwiperPagination( builder: , ), control: new SwiperControl(), ); }
This example involves the relevant knowledge of JSON to MODEL
The above is the detailed content of the basic use of Flutter Network Request Library DIO. For more information on the use of Flutter Network Request Library DIO, please pay attention to my other related articles!