| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import '../../core/constants.dart';
- import '../../database/database.dart';
- import 'database_provider.dart';
- import '../../services/auth_service.dart';
- import 'sync_provider.dart';
- class AuthState {
- final Agente? agente;
- final bool isLoading;
- final bool isInitialized;
- final String? error;
- const AuthState({
- this.agente,
- this.isLoading = false,
- this.isInitialized = false,
- this.error,
- });
- bool get isLoggedIn => agente != null;
- }
- final authServiceProvider = Provider<AuthService>((ref) {
- return AuthService(
- ref.read(agentiDaoProvider),
- ref.read(apiServiceProvider),
- ref.read(parametriDaoProvider),
- );
- });
- class AuthNotifier extends Notifier<AuthState> {
- @override
- AuthState build() {
- _checkInitialized();
- return const AuthState();
- }
- Future<void> _checkInitialized() async {
- final authService = ref.read(authServiceProvider);
- final initialized = await authService.isInitialized();
- state = AuthState(isInitialized: initialized);
- }
- Future<void> login(String code, String password, String url) async {
- state = const AuthState(isLoading: true);
- try {
- await ref.read(parametriDaoProvider).set(AppConstants.kUrlParam, url);
- final authService = ref.read(authServiceProvider);
- final agente = await authService.login(code, password);
- if (agente != null) {
- state = AuthState(agente: agente, isInitialized: true);
- } else {
- state = const AuthState(
- error: 'Codice agente o password errati',
- isInitialized: true,
- );
- }
- } catch (e) {
- state = AuthState(error: e.toString(), isInitialized: true);
- }
- }
- Future<void> initialize({
- required String codAgente,
- required String password,
- String? ragioneSociale,
- required String url,
- }) async {
- state = const AuthState(isLoading: true);
- try {
- final authService = ref.read(authServiceProvider);
- await authService.initializeAgent(
- codAgente: codAgente,
- pwd: password,
- ragioneSociale: ragioneSociale,
- url: url,
- );
- final agente = await authService.login(codAgente, password);
- state = AuthState(agente: agente, isInitialized: true);
- } catch (e) {
- state = AuthState(error: e.toString(), isInitialized: true);
- }
- }
- void logout() {
- state = const AuthState(isInitialized: true);
- }
- void resetToInit() {
- state = const AuthState(isInitialized: false);
- }
- }
- final authProvider = NotifierProvider<AuthNotifier, AuthState>(
- AuthNotifier.new,
- );
|