Flutter網(wǎng)絡(luò)請求庫DIO的基本使用
1. 導(dǎo)入dio包
目前dio庫的最新版本是3.0.1,同使用其他三方庫一樣,F(xiàn)lutter中使用dio庫同樣需要配置pubspec.yaml文件。
dependencies:
flutter:
sdk: flutter
dio: ^3.0.10
2. 導(dǎo)入并創(chuàng)建實例
dio包引入成功之后就可以創(chuàng)建dio實例了,一個實例可以發(fā)起多個請求,APP中如果只有一個數(shù)據(jù)源的情況下就可以考慮將dio實例創(chuàng)建成單例模式,這樣可以節(jié)省系統(tǒng)資源,減少不必要的開銷。
//htpp.dart import 'package:dio/dio.dart'; var dio = Dio();
3.基本配置
在開始使用實例之前需要對實例進行一些基本設(shè)置,由于每個人的項目需求不同,我這里只寫一下我自己小項目的幾個簡單配置:
//統(tǒng)一配置dio dio.options.baseUrl = "https://www.wanandroid.com";//baseUrl dio.options.connectTimeout = 5000;//超時時間 dio.options.receiveTimeout = 3000;//接收數(shù)據(jù)最長時間 dio.options.responseType = ResponseType.json;//數(shù)據(jù)格式
也可以通過創(chuàng)建option的方式配置:
BaseOptions options = BaseOptions(); options.baseUrl = "https://www.wanandroid.com"; options.connectTimeout = 5000; options.receiveTimeout = 3000; options.responseType = ResponseType.json; dio.options = options;
上面介紹了配置dio實例的兩種方式,并對其中的baseUrl、鏈接超時、接收數(shù)據(jù)最長時長、接收報文的數(shù)據(jù)類型等幾個簡單屬性做了統(tǒng)一配置。dio中還有一些其他的配置,可以參考dio的主頁github.com/flutterchin…
4.使用示例
dio實例配置完成之后如何使用呢?通過請求玩android首頁的banner圖來演示一下: 基本的步驟是,第一步先請求數(shù)據(jù),第二步把請求回來的json數(shù)據(jù)轉(zhuǎn)成model,第三步把model數(shù)據(jù)渲染成輪播圖:
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(),
);
},
),
//根據(jù)接口返回的數(shù)據(jù)生成輪播圖
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轉(zhuǎn)MODEL的相關(guān)知識
以上就是Flutter網(wǎng)絡(luò)請求庫DIO的基本使用的詳細內(nèi)容,更多關(guān)于Flutter網(wǎng)絡(luò)請求庫DIO的使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Flutter開發(fā)之設(shè)置應(yīng)用名稱及圖標(biāo)的教程
這篇文章主要介紹了Flutter設(shè)置應(yīng)用名稱及圖標(biāo)的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Android 監(jiān)聽?wèi)?yīng)用前/后臺切換實例代碼
本篇文章主要介紹了Android 監(jiān)聽?wèi)?yīng)用前/后臺切換實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
Android中WebView加載網(wǎng)頁設(shè)置進度條
這篇文章主要為大家詳細介紹了Android中WebView加載網(wǎng)頁設(shè)置進度條,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
Android網(wǎng)絡(luò)請求-sign參數(shù)的設(shè)置方式
這篇文章主要介紹了Android網(wǎng)絡(luò)請求-sign參數(shù)的設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

