其他分享
首页 > 其他分享> > Flutter取消下载

Flutter取消下载

作者:互联网

一、前言

下载大文件时,不想等待,既可以选择取消下载。预览如下:

在这里插入图片描述

二、引用

dio

功能:网络请求。

地址:https://pub.dev/packages/dio

三、使用

如下功能:

  1. 下载进度条
  2. 取消下载
import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
/// 第三方
import 'package:get/get.dart';
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<Test> {

  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(); /// 一定要重新实例化
              var response = await Dio().get(
                  "https://pic.netbian.com/uploads/allimg/180826/113958-153525479855be.jpg",
                  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);
  }
}

标签:dio,20,Get,取消,dart,下载,import,Flutter,dp
来源: https://blog.csdn.net/qq_38779672/article/details/122308393