1.在flutter的根目录下找到pubspec.yaml,点击进入后在dependencies下添加 dio: ^2.1.0
dependencies:
flutter:
sdk: flutter
dio: ^2.1.0
2.在根目录的lib文件夹创建创建公共的数据请求文件夹 ajax_data,在文件夹里创建dio_http.dart文件,封装异步的http请求方法
import 'package:dio/dio.dart';//引入dio.dart
import 'dart:io';//引入dart的基本库io提供对I/O的支持
Future https(String methods, String api,Map<String,dynamic> obj)async{
print('显示参数,方式$methods,接口$api ,参数$obj');
//注意:请求参数的数据类型是Map,数据结构类型是key为String,value可以是任意类型dynamic
try {
Response response;
Dio dio = new Dio();
dio.options.baseUrl = "这里是接口的域名";
dio.options.connectTimeout = 5000;//链接超时,单位毫秒
dio.options.receiveTimeout = 3000;//接收超时,单位毫秒
// 更换ContentType
dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
dio.options.responseType = ResponseType.json;//定制接收的数据类型
//添加header头
dio.options.headers = {
"version":1.0.1,
"Authorization":'_token',
};
//这里是请求拦截
dio.interceptors.add(InterceptorsWrapper(
onRequest:(RequestOptions options){
print(options.contentType);
// Do something before request is sent
return options; //continue
// If you want to resolve the request with some custom data,
// you can return a `Response` object or return `dio.resolve(data)`.
// If you want to reject the request with a error message,
// you can return a `DioError` object or return `dio.reject(errMsg)`
},
onResponse:(Response response) {
// Do something with response data
return response; // continue
},
onError: (DioError e) {
// Do something with response error
return e;//continue
}
));
// 判断请求的方式调用dio不同的请求api
if(methods == "post"){
response = await dio.post(api, data: obj);
}else if(methods == 'get'){
response = await dio.get(api, queryParameters: obj);
}//注意get请求使用queryParameters接收参数,post请求使用data接收参数
return response;//返回请求结果
} catch (e) {
print('报错$e');
return e;
}
}
3.实现数据请求
在widget的Dart文件里获取请求数据:
(1)首先引入dio_http.dart文件;
(2)创建自定义的StatefulWidget ,并在里面创建http的请求调用dio_http.dart 中的https方法,我会在下面单独加粗标记
class PickCount extends StatefulWidget {
PickCount({Key key}) : super(key: key);
_PickCountState createState() => _PickCountState();
}
class _PickCountState extends State<PickCount> {
GetUserMsg userMsg;//创建用户信息类(这是自定义的)
@override
Widget build(BuildContext context) {
print('获赞数${userMsg}');
return Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
textNumber(userMsg.pab_num),//数据的传入
textName(' 排行数 '),
textNumber(userMsg.user_fab_num),//数据的传入
GestureDetector(
child: textName(' 分数 '),
onTap: (){
print('点击');
},
),
textNumber(userMsg.nab_num),//数据的传入
GestureDetector(
child: textName(' 人数'),
onTap: (){
print('点击');
},
),
],
);
}
//widget中简单放在widget
Text textNumber(int count){
return Text(
'$count',
style: TextStyle(
fontSize: ScreenUtil().setHeight(36),
color: Colors.white
),
);
}
//widget中简单放在widget
Text textName(String name){
return Text(
'$name',
style: TextStyle(
fontSize: ScreenUtil().setHeight(26),
color: Color.fromRGBO(254, 254, 254, 0.6),
),
);
}
//以下是调用https的函数
void getUserMsgEvt(){
Map<String,dynamic> msg = {
'user_id':'1234567890123'
};
https('post', '接口名',msg ).then((res){
// 获取任意类型的数据json
dynamic json = res.data['data'];
print('显示结果 $json');
setState(() {
//对json数据进行模型层处理;并赋予userMsg
userMsg = GetUserMsg.fromJson(json);
});
});
}
@override
void initState() {
super.initState();
//调用请求数据的接口
getUserMsgEvt();
}
}