Basic Use of Flutter Network Request Library DIO

  • 2021-12-12 05:50:33
  • OfStack

Directory 1. Import dio package 2. Import and create an instance 3. Basic configuration 4. Use the sample

1. Import the dio package

At present, the latest version of dio library is 3.0. 1, which is the same as using other 3 libraries. Using dio library in Flutter also needs to configure pubspec. yaml files.


dependencies:
  flutter:
    sdk: flutter
  dio: ^3.0.10

2. Import and create an instance

After dio package is successfully introduced, dio instance can be created, and one instance can initiate multiple requests. If there is only one data source in APP, dio instance can be considered to be created into singleton mode, which can save system resources and reduce unnecessary overhead.


//htpp.dart
import 'package:dio/dio.dart';
var dio = Dio();

3. Basic configuration

Before starting to use the instance, I need to make some basic settings for the instance. Because everyone's project requirements are different, I will only write a few simple configurations for my own small project here:


// Unified 1 Configure dio
  dio.options.baseUrl = "https://www.wanandroid.com";//baseUrl
  dio.options.connectTimeout = 5000;// Timeout time 
  dio.options.receiveTimeout = 3000;// Maximum time to receive data 
  dio.options.responseType = ResponseType.json;// Data format 

It can also be configured by creating option:


BaseOptions options = BaseOptions();
options.baseUrl = "https://www.wanandroid.com";
options.connectTimeout = 5000;
options.receiveTimeout = 3000;
options.responseType = ResponseType.json;
dio.options = options;

The above introduces two ways to configure dio instance, and makes a unified configuration for several simple attributes such as baseUrl, link timeout, maximum duration of receiving data, and data type of receiving message. There are 1 other configurations in dio, please refer to github. com/flutterchin on the home page of dio …

4. Use the sample

How to use the dio instance after it is configured? Demo 1 by requesting to play the banner diagram on the homepage of android: The basic steps are as follows: Step 1 requests data first, step 2 converts the requested json data into model, and step 3 renders model data into carousel diagram:


child: FutureBuilder(
            future: dio.get("/banner/json"),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                Response response = snapshot.data;
                Map bannerMap = json.decode(response.toString());
                var banner = HomeBanner.fromJson(bannerMap);
                if (snapshot.hasError) {
                  Fluttertoast.showToast(msg: snapshot.error.toString());
                } else {
                  return _getSwiper(banner.data);
                  // Fluttertoast.showToast(msg: banner.data[0].title);
                }
              }
              return Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
  // Generate carousel map according to the data returned by interface 
  Swiper _getSwiper(List<Datum> data) {
    imgs.clear();
    for (var i = 0; i < data.length; i++) {
      var image = Image.network(
        data[i].imagePath,
        fit: BoxFit.cover,
      );
      imgs.add(image);
    }
    return Swiper(
      itemWidth: double.infinity,
      itemHeight: 200,
      itemCount: imgs.length,
      itemBuilder: (BuildContext context, int index) {
        return imgs[index];
      },
      autoplay: true,
      pagination: new SwiperPagination(
        builder: SwiperPagination.dots,
      ),
      control: new SwiperControl(),
    );
  }

This example involves the knowledge of JSON to MODEL

The above is the Flutter network request library DIO basic use of the details, more information about the use of Flutter network request library DIO please pay attention to other related articles on this site!


Related articles: