撸了一个flutter断点续传下载。
基于dio,自配。
以下是源码,自取。
import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
/*
* 文件下载
* 懒加载单例
*/
class DownLoadManage {
//用于记录正在下载的url,避免重复下载
// var downloadingUrls = new List();
var downloadingUrls = new Map<String, CancelToken>();
// 单例公开访问点
factory DownLoadManage() => _getInstance();
// 静态私有成员,没有初始化
static DownLoadManage _instance;
// 私有构造函数
DownLoadManage._() {
// 具体初始化代码
}
// 静态、同步、私有访问点
static DownLoadManage _getInstance() {
if (_instance == null) {
_instance = DownLoadManage._();
}
return _instance;
}
/*
*下载
*/
Future download(url, savePath,
{ProgressCallback onReceiveProgress,
Function done,
Function failed}) async {
int downloadStart = 0;
bool fileExists = false;
File f = File(savePath);
if (await f.exists()) {
downloadStart = f.lengthSync();
fileExists = true;
}
print("开始:" + downloadStart.toString());
if (fileExists && downloadingUrls.containsKey(url)) {
//正在下载
return;
}
var dio = Dio();
int contentLength = await _getContentLength(dio, url);
if (downloadStart == contentLength) {
//存在本地文件,命中缓存
done();
return;
}