| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- import 'package:flutter/material.dart';
- import '../../data/models/user.dart';
- import '../../data/models/auth/login_request.dart';
- import '../../data/models/auth/register_request.dart';
- import '../../data/repositories/auth_repository.dart';
-
- class AuthProvider with ChangeNotifier {
- final AuthRepository authRepository;
-
- User? _user;
- bool _isLoading = false;
- String? _error;
-
- AuthProvider({required this.authRepository}) {
- _loadCurrentUser();
- }
-
- User? get user => _user;
- bool get isAuthenticated => _user != null;
- bool get isLoading => _isLoading;
- String? get error => _error;
-
- Future<void> _loadCurrentUser() async {
- final user = await authRepository.getCurrentUser();
- if (user != null) {
- _user = user.data;
- notifyListeners();
- }
- }
-
- Future<void> login(String username, String password) async {
- _isLoading = true;
- _error = null;
- notifyListeners();
-
- try {
- final response = await authRepository.login(
- LoginRequest(username: username, password: password),
- );
-
- if (response.success && response.data != null) {
- _user = response.data;
- _error = null;
- } else {
- _error = response.message;
- }
- } catch (e) {
- _error = '登录失败: $e';
- } finally {
- _isLoading = false;
- notifyListeners();
- }
- }
-
- Future<void> register(String username, String email, String password, String passwordConfirm, String? phone) async {
- _isLoading = true;
- _error = null;
- notifyListeners();
-
- try {
- final response = await authRepository.register(
- RegisterRequest(username: username, email: email, password: password, passwordConfirm: passwordConfirm),
- );
-
- if (response.success && response.data != null) {
- _user = response.data;
- _error = null;
- } else {
- _error = response.message;
- }
- } catch (e) {
- _error = '注册失败: $e';
- } finally {
- _isLoading = false;
- notifyListeners();
- }
- }
-
- Future<void> logout() async {
- await authRepository.logout();
- _user = null;
- notifyListeners();
- }
-
- Future<void> checkAuthStatus() async {
- final isLoggedIn = await authRepository.isLoggedIn();
- if (!isLoggedIn) {
- _user = null;
- } else {
- await _loadCurrentUser();
- }
- notifyListeners();
- }
-
- void clearError() {
- _error = null;
- notifyListeners();
- }
- }
|