58 lines
1.5 KiB
Dart
58 lines
1.5 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../models/user.dart';
|
|
import '../services/storage_service.dart';
|
|
import '../services/api_service.dart';
|
|
|
|
class AuthState {
|
|
final User? user;
|
|
final bool isLoading;
|
|
final String? error;
|
|
|
|
const AuthState({this.user, this.isLoading = false, this.error});
|
|
|
|
bool get isLoggedIn => user != null;
|
|
|
|
AuthState copyWith({User? user, bool? isLoading, String? error}) {
|
|
return AuthState(
|
|
user: user ?? this.user,
|
|
isLoading: isLoading ?? this.isLoading,
|
|
error: error,
|
|
);
|
|
}
|
|
}
|
|
|
|
class AuthNotifier extends StateNotifier<AuthState> {
|
|
AuthNotifier() : super(const AuthState()) {
|
|
_checkLoginStatus();
|
|
}
|
|
|
|
Future<void> _checkLoginStatus() async {
|
|
await storageService.init();
|
|
final user = storageService.getUser();
|
|
if (user != null) {
|
|
state = state.copyWith(user: user);
|
|
}
|
|
}
|
|
|
|
Future<void> login(String phone, String password) async {
|
|
state = state.copyWith(isLoading: true, error: null);
|
|
try {
|
|
final response = await apiService.login(phone, password);
|
|
final user = User.fromJson(response['user']);
|
|
await storageService.saveUser(user);
|
|
state = state.copyWith(user: user, isLoading: false);
|
|
} catch (e) {
|
|
state = state.copyWith(isLoading: false, error: e.toString());
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await storageService.clearUser();
|
|
state = const AuthState();
|
|
}
|
|
}
|
|
|
|
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
|
|
return AuthNotifier();
|
|
});
|