dio网络请求:
本实例使用dio版本:dio: ^3.0.9
网络处理模板:
import 'package:dio/dio.dart';
class HttpUtils{
static Dio dio;
static const String API_PREFIX = "自己的apl接口";
static const int CONNECT_TIMEOUT = 50000;
static const int RECRIVE_TIMEOUT = 20000;
static const String GET = 'get';
static const String POST = 'post';
static const String PUT = 'put';
static const String PATCH = 'patch';
static const String DELETE = 'delete';
static Future<String> request(
String url,{
data,method})
async{
data = data??{
};
method = method ?? "GET";
data.forEach((key,value){
if(url.indexOf(key) != -1){
url = url.replaceAll(':$key',value.toString());
}
});
print("请求地址:"+method+' '+url);
print("请求参数:"+data.toString());
Dio dio = createInstance();
var result;
try{
print("url:"+url);
Response response = await dio.request(url,queryParameters: data,options: new Options(method: method));
result =response.data;
print("响应数据:"+response.toString());
}on DioError catch(e){
print("请求错误"+e.toString());
}
return result.toString();
}
static Dio createInstance(){
if(dio == null){
BaseOptions options = new BaseOptions(
baseUrl: API_PREFIX,
connectTimeout: CONNECT_TIMEOUT,
receiveTimeout: RECRIVE_TIMEOUT,
);
dio = new Dio(options);
}
return dio;
}
static clear(){
dio = null;
}
}
使用:
var result = await HttpUtils.request(
"//如果为put或者delete在此添加",
//method: HttpUtils.传值方式,
例:method: HttpUtils.get,
data: {
//发送给后台的参数
});
var result_json = JSON.jsonDecode(result);
setState(() {
id = result_json['id'].toString();
});
if (id == "0") {
await _iostishi();
} else {
await _iosshibai();
}