import 'package:driverapp/config/shared_pref_kay.dart'; import 'package:driverapp/core/model/authentication/authenticated_user.dart'; import 'package:driverapp/core/model/authentication/login_request.dart'; import 'package:driverapp/core/service/authentication_service.dart'; import 'package:driverapp/core/service/client/base_app_client.dart'; import 'package:flutter/cupertino.dart'; import '../../locator.dart'; enum APP_STATUS { LOADING, UNAUTHENTICATED, AUTHENTICATED } class AuthenticationViewModel with ChangeNotifier { AuthenticationService _authenticationService = locator(); AuthenticatedUser user; bool isLogin = false; bool isLoading = false; bool isError = false; String error; AuthenticationViewModel() { getUser(); } getUser() async { if (user == null) { isLoading = true; notifyListeners(); var userProfile = await sharedPref.getObject(USER_PROFILE); if (userProfile != null) { user = AuthenticatedUser.fromJson( await sharedPref.getObject(USER_PROFILE)); isLogin = true; isLoading = false; notifyListeners(); } else { isLogin = false; isLoading = false; notifyListeners(); } } // else // { // isLogin = true; // isLoading = false; // notifyListeners(); // } } APP_STATUS get status { if (isLoading) { return APP_STATUS.LOADING; } else { if (isLogin) { return APP_STATUS.AUTHENTICATED; } else { return APP_STATUS.UNAUTHENTICATED; } } } login(LoginRequest loginRequest) async { isLoading = true; notifyListeners(); await _authenticationService.login(loginRequest); if (_authenticationService.hasError) { error = _authenticationService.error; isLoading = false; isError = true; notifyListeners(); } else { isLoading = false; isError = false; isLogin = true; await sharedPref.setObject( USER_PROFILE, _authenticationService.authenticatedUser); sharedPref.setString(TOKEN, _authenticationService.token); user = _authenticationService.authenticatedUser; notifyListeners(); } } logout() async { isLoading = false; isError = false; isLogin = false; await sharedPref.clear(); notifyListeners(); } }