Files
AI-Health/health_app/lib/providers/ai_consent_provider.dart

94 lines
2.3 KiB
Dart

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, AiConsentState>(
AiConsentNotifier.new,
);
class AiConsentNotifier extends Notifier<AiConsentState> {
@override
AiConsentState build() => const AiConsentState();
String _key(String userId) => '$aiConsentVersion:$userId';
Future<void> 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: 'Authorization status could not be loaded.',
);
}
}
Future<bool> 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: 'Authorization could not be saved.',
);
return false;
}
}
Future<bool> 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: 'Authorization could not be revoked.',
);
return false;
}
}
}