import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'auth_provider.dart' show localDbProvider; const aiConsentVersion = 'ai-data-consent-v1'; class AiConsentState { final bool isLoading; final bool isSaving; final bool granted; final String? userId; final String? error; const AiConsentState({ this.isLoading = true, this.isSaving = false, this.granted = false, this.userId, this.error, }); } final aiConsentProvider = NotifierProvider( AiConsentNotifier.new, ); class AiConsentNotifier extends Notifier { @override AiConsentState build() => const AiConsentState(); String _key(String userId) => '$aiConsentVersion:$userId'; Future load(String userId) async { state = AiConsentState(isLoading: true, userId: userId); try { final value = await ref.read(localDbProvider).read(_key(userId)); state = AiConsentState( isLoading: false, granted: value == 'granted', userId: userId, ); } catch (_) { state = AiConsentState( isLoading: false, userId: userId, error: '授权状态加载失败,请重试', ); } } Future grant(String userId) async { state = AiConsentState( isLoading: false, isSaving: true, granted: state.granted, userId: userId, ); try { await ref.read(localDbProvider).write(_key(userId), 'granted'); state = AiConsentState(isLoading: false, granted: true, userId: userId); return true; } catch (_) { state = AiConsentState( isLoading: false, userId: userId, error: '授权保存失败,请稍后重试', ); return false; } } Future revoke(String userId) async { state = AiConsentState( isLoading: false, isSaving: true, granted: state.granted, userId: userId, ); try { await ref.read(localDbProvider).delete(_key(userId)); state = AiConsentState(isLoading: false, granted: false, userId: userId); return true; } catch (_) { state = AiConsentState( isLoading: false, granted: true, userId: userId, error: '撤回授权失败,请稍后重试', ); return false; } } }