verify_code_view_model.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:domain/repository/auth_repository.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:plugin_platform/engine/directory/directory_util.dart';
  6. import 'package:plugin_platform/engine/toast/toast_engine.dart';
  7. import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
  8. import 'package:shared/utils/log_utils.dart';
  9. import 'verify_code_state.dart';
  10. class VerifyCodeViewModel extends AutoDisposeNotifier<verifyCodeState> with DioCancelableMixin {
  11. late final AuthRepository authRepository;
  12. @override
  13. verifyCodeState build() {
  14. authRepository = ref.read(authRepositoryProvider);
  15. final state = verifyCodeState();
  16. registerCancellation(callback: () {
  17. _clearCachedImage();
  18. });
  19. return state;
  20. }
  21. ///获取验证码
  22. void fetchCode() async {
  23. final result = await authRepository.fetchCaptchaImage(cancelToken: cancelToken);
  24. //Base64转为本地图片缓存
  25. final bytes = base64.decode(result.data?.img?.replaceFirst('data:image/png;base64,', '') ?? '');
  26. final tempDir = DirectoryUtil.getTempPath();
  27. final file = File('$tempDir/verify${DateTime.now().millisecondsSinceEpoch}.png');
  28. await file.writeAsBytes(bytes);
  29. Log.d('存入的File路径为:${file.path}');
  30. if (result.isSuccess) {
  31. state = state.copyWith(key: result.data?.key, imgFilePath: file.path);
  32. } else {
  33. ToastEngine.show(result.errorMsg ?? "UnKnow Error");
  34. }
  35. }
  36. // 清除缓存的verify验证图形码的缓存文件
  37. Future<void> _clearCachedImage() async {
  38. final cacheDir = await DirectoryUtil.initTempDir();
  39. if (cacheDir != null) {
  40. if (await cacheDir.exists()) {
  41. //遍历删除 Cache 目录下面的全部文件或文件夹
  42. for (final entity in cacheDir.listSync()) {
  43. // 如果是指定的文件直接删除
  44. if (entity is File && entity.path.split('/').last.startsWith("verify")) {
  45. await entity.delete();
  46. }
  47. }
  48. }
  49. }
  50. }
  51. }
  52. final verifyCodeProvider = NotifierProvider.autoDispose<VerifyCodeViewModel, verifyCodeState>(VerifyCodeViewModel.new);