79 lines
2.6 KiB
Dart
79 lines
2.6 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:wallpaper/common/components/view_state_widget.dart';
|
||
import 'package:wallpaper/common/network/dio_client.dart';
|
||
import 'package:wallpaper/common/utils/filesize_util.dart';
|
||
import 'package:wallpaper/common/utils/local_path_util.dart';
|
||
import 'package:wallpaper/common/utils/log_print.dart';
|
||
import 'package:wallpaper/common/utils/num_util.dart';
|
||
|
||
class DownloadUtil {
|
||
/// 下载壁纸
|
||
static Future downloadWallpaper(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).w,
|
||
snackPosition: SnackPosition.TOP,
|
||
backgroundColor: Colors.white,
|
||
titleText: const Text(
|
||
'Loading...',
|
||
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 = Directory(await LocalPathUtil.getTemporaryPath());
|
||
bool exist = await dir.exists();
|
||
if (!exist) {
|
||
// 若目录不存在,先创建
|
||
await dir.create();
|
||
}
|
||
// 获取图片文件的名称,使用uri来解析url
|
||
Uri uri = Uri.parse(imageUrl);
|
||
String savePath = '${dir.path}/${uri.pathSegments.last}';
|
||
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();
|
||
});
|
||
}
|
||
}
|