import 'dart:convert'; import 'dart:io'; import 'package:domain/repository/auth_repository.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:plugin_platform/engine/directory/directory_util.dart'; import 'package:plugin_platform/engine/toast/toast_engine.dart'; import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart'; import 'package:shared/utils/log_utils.dart'; import 'verify_code_state.dart'; class VerifyCodeViewModel extends AutoDisposeNotifier with DioCancelableMixin { late final AuthRepository authRepository; @override verifyCodeState build() { authRepository = ref.read(authRepositoryProvider); final state = verifyCodeState(); registerCancellation(callback: () { _clearCachedImage(); }); return state; } ///获取验证码 void fetchCode() async { final result = await authRepository.fetchCaptchaImage(cancelToken: cancelToken); //Base64转为本地图片缓存 final bytes = base64.decode(result.data?.img?.replaceFirst('data:image/png;base64,', '') ?? ''); final tempDir = DirectoryUtil.getTempPath(); final file = File('$tempDir/verify${DateTime.now().millisecondsSinceEpoch}.png'); await file.writeAsBytes(bytes); Log.d('存入的File路径为:${file.path}'); if (result.isSuccess) { state = state.copyWith(key: result.data?.key, imgFilePath: file.path); } else { ToastEngine.show(result.errorMsg ?? "UnKnow Error"); } } // 清除缓存的verify验证图形码的缓存文件 Future _clearCachedImage() async { final cacheDir = await DirectoryUtil.initTempDir(); if (cacheDir != null) { if (await cacheDir.exists()) { //遍历删除 Cache 目录下面的全部文件或文件夹 for (final entity in cacheDir.listSync()) { // 如果是指定的文件直接删除 if (entity is File && entity.path.split('/').last.startsWith("verify")) { await entity.delete(); } } } } } } final verifyCodeProvider = NotifierProvider.autoDispose(VerifyCodeViewModel.new);