app_service.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'dart:io';
  2. import 'package:ctjt_flutter/common/states.dart';
  3. import 'package:ctjt_flutter/model/version_res.dart';
  4. import 'package:ctjt_flutter/service/base_service.dart';
  5. import 'package:dio/dio.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:path_provider/path_provider.dart';
  8. import 'package:provider/provider.dart';
  9. class AppService extends BaseService {
  10. late BuildContext mContext;
  11. AppService._();
  12. static final _instance = AppService._();
  13. factory AppService.getInstance(BuildContext context) {
  14. _instance.mContext = context;
  15. return _instance;
  16. }
  17. /// 拉取版本号信息
  18. Future<VersionResBody?> fetchVersionInfo(String v) async {
  19. int channelType = HTTPConfig.getChannelType(); // 根据环境判断更新渠道类型
  20. var uri = '/common/getAppVersion?currentVersion=' + v + '&channelType=' + channelType.toString();
  21. var data = await request(uri);
  22. if (null == data) {
  23. return null;
  24. }
  25. var ver = VersionRes.fromJson(data);
  26. print("Got version from remote:" + ver.body!.lastVersion!);
  27. return ver.body;
  28. }
  29. /// 下载安卓更新包
  30. Future<File?> downloadAndroid(String url, String version) async {
  31. /// 创建存储文件
  32. Directory? storageDir = await getExternalStorageDirectory();
  33. if (null == storageDir) {
  34. return null;
  35. }
  36. String storagePath = storageDir.path;
  37. File file = new File('$storagePath/ctjt_flutter_install_$version.apk');
  38. if (!file.existsSync()) {
  39. file.createSync();
  40. }
  41. /// 发起下载请求
  42. Response? response = await requestFile(url,
  43. onReceiveProgress: showDownloadProgress);
  44. if (null == response) {
  45. return null;
  46. }
  47. file.writeAsBytesSync(response.data);
  48. return file;
  49. }
  50. /// 展示下载进度
  51. void showDownloadProgress(num received, num total) {
  52. if (total != -1) {
  53. double _progress =
  54. double.parse('${(received / total).toStringAsFixed(2)}');
  55. print('Download process is $_progress');
  56. Provider.of<AppDownloadProcess>(mContext, listen: false).process =
  57. _progress;
  58. }
  59. }
  60. }