import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../../core/storage/secure_storage.dart'; import '../../../../core/storage/storage_keys.dart'; import '../../../../core/di/injection_container.dart'; enum AuthStatus { initial, checking, authenticated, unauthenticated, } class AuthState { final AuthStatus status; final String? walletAddress; final bool isWalletCreated; final bool isFirstLaunch; final bool hasSeenGuide; final String? errorMessage; const AuthState({ this.status = AuthStatus.initial, this.walletAddress, this.isWalletCreated = false, this.isFirstLaunch = true, this.hasSeenGuide = false, this.errorMessage, }); AuthState copyWith({ AuthStatus? status, String? walletAddress, bool? isWalletCreated, bool? isFirstLaunch, bool? hasSeenGuide, String? errorMessage, }) { return AuthState( status: status ?? this.status, walletAddress: walletAddress ?? this.walletAddress, isWalletCreated: isWalletCreated ?? this.isWalletCreated, isFirstLaunch: isFirstLaunch ?? this.isFirstLaunch, hasSeenGuide: hasSeenGuide ?? this.hasSeenGuide, errorMessage: errorMessage, ); } } class AuthNotifier extends StateNotifier { final SecureStorage _secureStorage; AuthNotifier(this._secureStorage) : super(const AuthState()); Future checkAuthStatus() async { state = state.copyWith(status: AuthStatus.checking); try { // 检查是否首次启动 final isFirstLaunchStr = await _secureStorage.read(key: StorageKeys.isFirstLaunch); final isFirstLaunch = isFirstLaunchStr == null || isFirstLaunchStr != 'false'; // 检查钱包状态 final walletAddress = await _secureStorage.read(key: StorageKeys.walletAddress); final isWalletCreated = walletAddress != null && walletAddress.isNotEmpty; if (isWalletCreated) { state = state.copyWith( status: AuthStatus.authenticated, walletAddress: walletAddress, isWalletCreated: true, isFirstLaunch: false, hasSeenGuide: true, ); } else { state = state.copyWith( status: AuthStatus.unauthenticated, isWalletCreated: false, isFirstLaunch: isFirstLaunch, hasSeenGuide: !isFirstLaunch, ); } } catch (e) { state = state.copyWith( status: AuthStatus.unauthenticated, errorMessage: e.toString(), ); } } /// 标记已查看向导页 Future markGuideAsSeen() async { await _secureStorage.write(key: StorageKeys.isFirstLaunch, value: 'false'); state = state.copyWith( isFirstLaunch: false, hasSeenGuide: true, ); } Future saveWallet(String walletAddress, String privateKey) async { await _secureStorage.write(key: StorageKeys.walletAddress, value: walletAddress); await _secureStorage.write(key: StorageKeys.privateKey, value: privateKey); state = state.copyWith( status: AuthStatus.authenticated, walletAddress: walletAddress, isWalletCreated: true, ); } Future logout() async { await _secureStorage.deleteAll(); state = const AuthState(status: AuthStatus.unauthenticated); } } final authProvider = StateNotifierProvider((ref) { final secureStorage = ref.watch(secureStorageProvider); return AuthNotifier(secureStorage); });