2026-01-19 14:50:21 +08:00
|
|
|
import 'package:flutter/material.dart';
|
2026-02-26 06:35:57 +08:00
|
|
|
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;
|
2026-01-19 14:50:21 +08:00
|
|
|
|
|
|
|
|
class AuthState extends ChangeNotifier {
|
2026-02-26 06:35:57 +08:00
|
|
|
final AuthService _authService;
|
|
|
|
|
|
|
|
|
|
AuthState(this._authService) {
|
|
|
|
|
_authService.user.listen(_onUserChanged);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool _isLoading = false;
|
|
|
|
|
bool get isLoading => _isLoading;
|
|
|
|
|
|
2026-01-19 14:56:39 +08:00
|
|
|
bool _isLoggedIn = false;
|
|
|
|
|
bool get isLoggedIn => _isLoggedIn;
|
2026-01-19 14:50:21 +08:00
|
|
|
|
2026-02-26 06:35:57 +08:00
|
|
|
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;
|
2026-01-19 15:48:09 +08:00
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-26 06:35:57 +08:00
|
|
|
Future<void> signInWithPhoneNumber(String phoneNumber) async {
|
|
|
|
|
_isLoading = true;
|
|
|
|
|
_errorMessage = null;
|
2026-01-19 14:56:39 +08:00
|
|
|
notifyListeners();
|
2026-02-26 06:35:57 +08:00
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
2026-01-19 14:50:21 +08:00
|
|
|
}
|
|
|
|
|
}
|