Flutter網絡請求庫DIO的使用

1. 導入dio包

目前dio庫的最新版本是3.0.1,同使用其餘三方庫同樣,Flutter中使用dio庫一樣須要配置pubspec.yaml文件。android

dependencies:
  flutter:
    sdk: flutter
  dio: ^3.0.10
複製代碼

2. 導入並建立實例

dio包引入成功以後就能夠建立dio實例了,一個實例能夠發起多個請求,APP中若是隻有一個數據源的狀況下就能夠考慮將dio實例建立成單例模式,這樣能夠節省系統資源,減小沒必要要的開銷。git

//htpp.dart
import 'package:dio/dio.dart';
var dio = Dio();
複製代碼

3.基本配置

在開始使用實例以前須要對實例進行一些基本設置,因爲每一個人的項目需求不一樣,我這裏只寫一下我本身小項目的幾個簡單配置:github

//統一配置dio
  dio.options.baseUrl = "https://www.wanandroid.com";//baseUrl
  dio.options.connectTimeout = 5000;//超時時間
  dio.options.receiveTimeout = 3000;//接收數據最長時間
  dio.options.responseType = ResponseType.json;//數據格式
複製代碼

也能夠經過建立option的方式配置:json

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

上面介紹了配置dio實例的兩種方式,並對其中的baseUrl、連接超時、接收數據最長時長、接收報文的數據類型等幾個簡單屬性作了統一配置。dio中還有一些其餘的配置,能夠參考dio的主頁github.com/flutterchin…markdown

4.使用示例

dio實例配置完成以後如何使用呢?經過請求玩android首頁的banner圖來演示一下: 基本的步驟是,第一步先請求數據,第二步把請求回來的json數據轉成model,第三步把model數據渲染成輪播圖:oop

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(),
              );
            },
          ),
  //根據接口返回的數據生成輪播圖
  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(),
    );
  }
複製代碼

這個示例中涉及到了JSON轉MODEL的相關知識,能夠參考個人另外一篇文章Flutter Json轉model的幾種方式,這裏不作單獨介紹了。ui

相關文章
相關標籤/搜索