在写service_method.dart的时候,你会发现我们大部分的代码都是相同的,甚至复制一个方法后,通过简单的修改几个地方,就可以使用了。那就说明这个地方由优化的必要。让代码更通用更精简。
精简代码如下:
Future request(url,formData)async{
try{
print('开始获取数据...............');
Response response;
Dio dio = new Dio();
dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
if(formData==null){
response = await dio.post(servicePath[url]);
}else{
response = await dio.post(servicePath[url],data:formData);
}
if(response.statusCode==200){
return response.data;
}else{
throw Exception('后端接口出现异常,请检测代码和服务器情况.........');
}
}catch(e){
return print('ERROR:======>${e}');
}
}
上面通用方法的时候,我们的参数使用了一个必选参数,其实我们可以使用一个可选参数。Dart中的可选参数,直接使用“{}”(大括号)就可以了。可选参数在调用的时候必须使用paramName:value的形式。
我们把上面的后端接口代码改为如下:
Future request(url,{formData})async{
try{
print('开始获取数据...............');
Response response;
Dio dio = new Dio();
dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
if(formData==null){
response = await dio.post(servicePath[url]);
}else{
response = await dio.post(servicePath[url],data:formData);
}
if(response.statusCode==200){
return response.data;
}else{
throw Exception('后端接口出现异常,请检测代码和服务器情况.........');
}
}catch(e){
return print('ERROR:======>${e}');
}
}










网友评论