Agrego frontend app
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:gimnasio_soma/features/auth/data/repositories/auth_repository_impl.dart';
|
||||
import 'package:gimnasio_soma/features/auth/domain/entities/user_session.dart';
|
||||
import 'package:gimnasio_soma/features/auth/domain/repositories/auth_repository.dart';
|
||||
|
||||
final authRepositoryProvider = Provider<AuthRepository>((ref) {
|
||||
return AuthRepositoryImpl();
|
||||
});
|
||||
|
||||
final authStateProvider =
|
||||
StateNotifierProvider<AuthNotifier, AsyncValue<UserSession?>>((ref) {
|
||||
return AuthNotifier(ref.read(authRepositoryProvider));
|
||||
});
|
||||
|
||||
/// Listenable que notifica al GoRouter cuando cambia el estado de auth.
|
||||
/// Solo notifica cuando el estado pasa de logueado a no-logueado o viceversa,
|
||||
/// no cuando pasa a loading (para evitar recrear el router innecesariamente).
|
||||
final authChangeNotifierProvider = Provider<AuthChangeNotifier>((ref) {
|
||||
final notifier = AuthChangeNotifier();
|
||||
ref.listen<AsyncValue<UserSession?>>(authStateProvider, (prev, next) {
|
||||
final wasLoggedIn = prev?.valueOrNull != null;
|
||||
final isLoggedIn = next.valueOrNull != null;
|
||||
if (wasLoggedIn != isLoggedIn) {
|
||||
notifier.notify();
|
||||
}
|
||||
});
|
||||
return notifier;
|
||||
});
|
||||
|
||||
class AuthChangeNotifier extends ChangeNotifier {
|
||||
void notify() => notifyListeners();
|
||||
}
|
||||
|
||||
class AuthNotifier extends StateNotifier<AsyncValue<UserSession?>> {
|
||||
final AuthRepository _repository;
|
||||
|
||||
AuthNotifier(this._repository) : super(const AsyncValue.data(null));
|
||||
|
||||
Future<void> checkSession() async {
|
||||
state = const AsyncValue.loading();
|
||||
try {
|
||||
final session = await _repository.validateSession();
|
||||
state = AsyncValue.data(session);
|
||||
} catch (e, st) {
|
||||
state = AsyncValue.error(e, st);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> login(String dni, String password) async {
|
||||
try {
|
||||
final session = await _repository.login(dni, password);
|
||||
state = AsyncValue.data(session);
|
||||
return null;
|
||||
} catch (e) {
|
||||
state = const AsyncValue.data(null);
|
||||
return e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _repository.logout();
|
||||
state = const AsyncValue.data(null);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user