下载大文件时,不想等待,既可以选择取消下载。预览如下:
功能:网络请求。
地址:https://pub.dev/packages/dio
如下功能:
- 下载进度条
- 取消下载
- 拦截器
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions requestOptions, RequestInterceptorHandler handler){
print("请求之前");
handler.next(requestOptions);
}, onResponse: (Response response, ResponseInterceptorHandler handler){
print("响应之前");
handler.next(response);
}, onError: (DioError error, ErrorInterceptorHandler handler){
print("错误之前");
setState(() {
_process = 0.0;
});
handler.next(error);
}
));
import 'package:dio/dio.dart';
/// 第三方
import 'package:get/get.dart' hide Response;
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
/// 本地资源
import '../../theme/utils/export.dart';
import '../../utils/widget/common.dart';
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State {
var _process = 0.0;
late CancelToken token;
/// 主内容
Widget mainBody(BuildContext context){
return Column(
children: [
safePadding(context, c_FF),
customerHeader(context, c_FF, "Dio取消请求", leftContent: GestureDetector(
onTap: ()=>Get.back(),
child: Image.asset(
R.imagesCommonBackIcon,
width: 24.dp,
height: 24.dp,
),
)),
Get.getHeightBox(20.dp),
GestureDetector(
onTap: () async {
/// dio使用get下载文件
try{
token = CancelToken();
Dio dio = new Dio();
/// dio拦截器部分--开始
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions requestOptions, RequestInterceptorHandler handler){
print("请求之前");
handler.next(requestOptions);
}, onResponse: (Response response, ResponseInterceptorHandler handler){
print("响应之前");
handler.next(response);
}, onError: (DioError error, ErrorInterceptorHandler handler){
print("错误之前");
setState(() {
_process = 0.0;
});
handler.next(error);
}
));
/// dio拦截器部分--结束
var response = await dio.get(
"https://pic.netbian.com/uploads/allimg/180826/113958-153525479855be.",
cancelToken: token,
onReceiveProgress: (num received, num total){ /// 获取下载进度
setState(() {
_process = double.parse('${(received / total).toStringAsFixed(2)}');
});
},
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
)
);
print(response);
} on DioError catch(e) {
print("response.statusCode: ${e.type}");
}
},
child: Text("请求数据"),
),
Get.getHeightBox(20.dp),
CircularProgressIndicator(
value: _process,
),
Get.getHeightBox(20.dp),
Text("下载进度:${_process*100}%"),
Get.getHeightBox(20.dp),
GestureDetector(
onTap: ()=>{
token.cancel()
},
child: Text("取消请求"),
),
Get.getHeightBox(20.dp),
],
);
}
@override
Widget build(BuildContext context) {
return customerTheme(false, SystemUiOverlayStyle.dark, mainBody(context), boxDecoration: BoxDecoration(
color: c_FC
), willPop: true);
}
}