initializeAuth method
Initializes the authentication state from shared_preferences
.
Attempts to load the authentication token, user, and hospital data from persistent storage. If successful, the user is considered authenticated. If an error occurs, it logs out the user.
Implementation
Future<void> initializeAuth() async {
_setLoading(true);
try {
final prefs = await SharedPreferences.getInstance();
final tokenStr = prefs.getString('authToken');
final userStr = prefs.getString('user');
final hospitalStr = prefs.getString('hospital');
if (tokenStr != null && userStr != null && hospitalStr != null) {
_token = tokenStr;
_user = User.fromJson(jsonDecode(userStr));
_hospital = Hospital.fromJson(jsonDecode(hospitalStr));
_clearError();
notifyListeners();
}
} catch (e) {
_setError('Failed to initialize authentication: ${e.toString()}');
await logout();
} finally {
_setLoading(false);
}
}