76 lines
2.5 KiB
Dart
76 lines
2.5 KiB
Dart
// Author: fengshengxiong
|
|
// Date: 2024/5/10
|
|
// Description: 下载文件
|
|
|
|
import 'dart:io';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:hello_wallpaper/common/components/view_state_widget.dart';
|
|
import 'package:hello_wallpaper/common/network/dio_client.dart';
|
|
import 'package:hello_wallpaper/common/utils/filesize_util.dart';
|
|
import 'package:hello_wallpaper/common/utils/local_path_util.dart';
|
|
import 'package:hello_wallpaper/common/utils/log_print.dart';
|
|
import 'package:hello_wallpaper/common/utils/num_util.dart';
|
|
|
|
class DownloadUtil {
|
|
/// 下载文件
|
|
static Future downloadFile(String imageUrl, Function(String savePath) callBack) async {
|
|
var process = 0.0.obs;
|
|
var processStr = ''.obs;
|
|
var cancelToken = CancelToken();
|
|
Get.showSnackbar(GetSnackBar(
|
|
borderRadius: 8.r,
|
|
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16).w,
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.white,
|
|
titleText: const Text(
|
|
'downloading...',
|
|
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
|
|
),
|
|
messageText: Obx(() {
|
|
return Row(
|
|
children: [
|
|
loadingView(
|
|
valueColor: const AlwaysStoppedAnimation<Color>(Colors.black),
|
|
value: process.value,
|
|
),
|
|
SizedBox(width: 10.w),
|
|
Expanded(
|
|
child: Text(
|
|
processStr.value,
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: TextStyle(
|
|
fontSize: 14.sp,
|
|
color: Colors.black,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}),
|
|
));
|
|
Directory dir = await LocalPathUtil.getTemporaryPath();
|
|
bool exist = await dir.exists();
|
|
if (!exist) {
|
|
// 若目录不存在,先创建
|
|
await dir.create();
|
|
}
|
|
String savePath = '${dir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
|
|
LogPrint.d('壁纸保存位置:$savePath');
|
|
await DioClient().download(imageUrl, savePath, cancelToken: cancelToken, onReceiveProgress: (int count, int total) {
|
|
if (total != -1) {
|
|
process.value = NumUtil.strToDouble(NumUtil.formatNum(count / total));
|
|
processStr.value = '${FileSizeUtil.fileSize(count)}/${FileSizeUtil.fileSize(total)}';
|
|
}
|
|
}, success: () {
|
|
Get.back();
|
|
callBack(savePath);
|
|
}, fail: (err) {
|
|
Get.back();
|
|
});
|
|
}
|
|
}
|