dio是目前比较流行的网络请求框架。
一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等...
实现过程
1、引入Dio框架,在pubspec.yaml文件中的dependencies标签下面写即可
dio:^5.1.2
2、在你需要网络请求的页面,引入头文件import 'package:dio/dio.dart';
3、实现代码
一个最简单的get请求
//网络请求
void _getMyInfoRequest()async{
Response response;
var dio =Dio();
response =await dio.get('http://guolin.tech/api/china');
print('get网络请求:'+response.data.toString());
}
一个简单的post带参数请求
Map params = {
"id":89113,
};
response = await dio.post(HttpConfig.baseUrl+HttpConfig.userInfo,queryParameters:params);
print(resp.msg);
print(resp.code);
print('post网络请求:'+resp.data.toString());
model类
StoreDetailData.dart文件:
class StoreDetailData {
int?id;
String?cover;
String?name;
String?address;
String?telephone;
StoreDetailData();
StoreDetailData.fromJson(Map json) {
id = json['id'];
cover = json['storeDoorstep'];
name = json['storeName'];
address = json['address']; //??
telephone = json['telephone'];
}
}
StoreListVModel.dart文件:
class StoreListVModel extends ChangeNotifier {
StoreListVModel({this.scriptId = -1});
final intscriptId;
Liststores = [];
int_pageIndex =0;
bool_fullLoaded =false;
intget pageIndex =>_pageIndex;
boolget fullLoaded =>_fullLoaded;
@override
void dispose() {
stores.clear();
_pageIndex =0;
super.dispose();
}
FuturegetStoresPaged(int page)async {
if (page <=0) page =1;
Map params = {
"latitude": AccManager.defaultLongitude,//defaultLongitude/locLatitude
"longitude": AccManager.defaultLatitude,//defaultLatitude/locLongitude
"pageNo": page,
"pageSize": defaultPagedSize,
};
if (scriptId != -1) {
params['dramaId'] =scriptId;
}
BaseResp resp =await HttpUtil().request(
-1 !=scriptId ? HttpConfig.storeList: HttpConfig.storeListAround,
params: params,
);
if (resp.success()) {
List tmp = StoreListData.listFromJson(resp.data);
if (tmp.isEmpty)return;
if (page <=1) {
stores.clear();
}
stores.addAll(tmp);
_pageIndex = page;
_fullLoaded =_pageIndex >= StoreListData.totalPages;
notifyListeners();
}
}
FuturegetNextPage() => getStoresPaged(_pageIndex +1);
}
。。。