Files
phone_login/lib/auth/auth_state.dart
soragui c903430f75 refactor: implement Flutter best practices and proper architecture
- Create proper service layer with AuthService and FirebaseAuthService
- Implement UserModel for proper data representation
- Enhance AuthState with proper loading states and error handling
- Convert stateless widgets to stateful where appropriate
- Add proper form validation and user feedback mechanisms
- Implement comprehensive error handling and loading indicators
- Fix redirect logic in router for proper authentication flow
- Create theme system with light and dark themes
- Add shared components like LoadingIndicator
- Improve code organization following recommended architecture
- Add proper disposal of controllers and focus nodes
- Implement proper null safety handling

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 06:35:57 +08:00

83 lines
1.9 KiB
Dart

import 'package:flutter/material.dart';
import 'package:phone_login/services/auth_service.dart';
import 'package:phone_login/shared/models/user_model.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase;
class AuthState extends ChangeNotifier {
final AuthService _authService;
AuthState(this._authService) {
_authService.user.listen(_onUserChanged);
}
bool _isLoading = false;
bool get isLoading => _isLoading;
bool _isLoggedIn = false;
bool get isLoggedIn => _isLoggedIn;
String? _errorMessage;
String? get errorMessage => _errorMessage;
UserModel? _currentUser;
UserModel? get currentUser => _currentUser;
void _onUserChanged(firebase.User? user) {
if (user != null) {
_isLoggedIn = true;
_currentUser = UserModel.fromFirebaseUser(user);
} else {
_isLoggedIn = false;
_currentUser = null;
}
_isLoading = false;
notifyListeners();
}
Future<void> signInWithPhoneNumber(String phoneNumber) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
await _authService.signInWithPhoneNumber(phoneNumber);
} on Exception catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> verifyOTP(String verificationId, String otp) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
await _authService.verifyOTP(verificationId, otp);
} on Exception catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> logout() async {
_isLoading = true;
notifyListeners();
try {
await _authService.signOut();
_isLoggedIn = false;
_currentUser = null;
} on Exception catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
}