Files
tm_app/lib/view_models/auth_view_model.dart
T
amirrezaghabeli f81e9dd32d fixed login bug
2025-08-21 10:59:28 +03:30

112 lines
3.0 KiB
Dart

import 'package:flutter/material.dart';
import 'package:tm_app/data/services/model/customer/customer.dart';
import '../core/utils/result.dart';
import '../data/repositories/auth_repository.dart';
import '../data/services/model/login_response/login_response_model.dart';
import '../data/services/model/logout_response/logout_response.dart';
class AuthViewModel with ChangeNotifier {
final AuthRepository _authRepository;
AuthViewModel({required AuthRepository authRepository})
: _authRepository = authRepository {
usernameController.addListener(_onTextChanged);
passwordController.addListener(_onTextChanged);
// usernameFocus.addListener(_onTextChanged);
// passwordFocus.addListener(_onTextChanged);
}
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final FocusNode usernameFocus = FocusNode();
final FocusNode passwordFocus = FocusNode();
bool _obscurePassword = true;
bool get obscurePassword => _obscurePassword;
bool get isLoginEnabled =>
usernameController.text.isNotEmpty && passwordController.text.isNotEmpty;
// Auth state
bool _isLoading = false;
String? _errorMessage;
Customer? _loggedInUser;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
Customer? get loggedInUser => _loggedInUser;
void togglePasswordVisibility() {
_obscurePassword = !_obscurePassword;
notifyListeners();
}
void _onTextChanged() {
notifyListeners();
}
Future<void> login() async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
final result = await _authRepository.login(
username: usernameController.text.trim(),
password: passwordController.text.trim(),
);
switch (result) {
case Ok<LoginResponseModel>():
_loggedInUser = result.value.data.customer;
usernameController.text.trim();
passwordController.text.trim();
usernameController.clear();
passwordController.clear();
break;
case Error<LoginResponseModel>():
_errorMessage = result.error.toString();
break;
}
_isLoading = false;
notifyListeners();
_errorMessage = null;
notifyListeners();
}
Future<void> localLogout() async {
await _authRepository.localLogout();
_loggedInUser = null;
notifyListeners();
}
Future<void> logout() async {
_errorMessage = null;
notifyListeners();
final result = await _authRepository.logout();
switch (result) {
case Ok<LogoutResponse>():
localLogout();
break;
case Error<LogoutResponse>():
_errorMessage = result.error.toString();
break;
}
notifyListeners();
_errorMessage = null;
notifyListeners();
}
@override
void dispose() {
usernameController.dispose();
passwordController.dispose();
usernameFocus.dispose();
passwordFocus.dispose();
super.dispose();
}
}