72 lines
1.9 KiB
Dart
72 lines
1.9 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:ontime_user_flutter/data/api/api_client.dart';
|
|
import 'package:ontime_user_flutter/features/auth/data/auth_api.dart';
|
|
import 'package:ontime_user_flutter/features/auth/data/models/user_model.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class AuthState {
|
|
const AuthState({
|
|
this.user,
|
|
this.isLoading = false,
|
|
this.errorMessage,
|
|
});
|
|
|
|
final UserModel? user;
|
|
final bool isLoading;
|
|
final String? errorMessage;
|
|
|
|
AuthState copyWith({
|
|
UserModel? user,
|
|
bool? isLoading,
|
|
String? errorMessage,
|
|
}) {
|
|
return AuthState(
|
|
user: user ?? this.user,
|
|
isLoading: isLoading ?? this.isLoading,
|
|
errorMessage: errorMessage,
|
|
);
|
|
}
|
|
}
|
|
|
|
final authControllerProvider =
|
|
StateNotifierProvider<AuthController, AuthState>((ref) {
|
|
return AuthController();
|
|
});
|
|
|
|
class AuthController extends StateNotifier<AuthState> {
|
|
AuthController() : super(const AuthState());
|
|
|
|
late final AuthApi _api =
|
|
AuthApi(ApiClient(basicAuthUser: null, basicAuthPassword: null));
|
|
|
|
Future<void> login({
|
|
String? phone,
|
|
String? email,
|
|
required String password,
|
|
String? fcmToken,
|
|
}) async {
|
|
state = state.copyWith(isLoading: true, errorMessage: null);
|
|
try {
|
|
final user = await _api.login(
|
|
phone: phone,
|
|
email: email,
|
|
password: password,
|
|
fcmToken: fcmToken,
|
|
);
|
|
state = state.copyWith(user: user, isLoading: false);
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString('user_id', user.id);
|
|
await prefs.setString('user_token', user.token);
|
|
await prefs.setString('user_phone', user.phone);
|
|
await prefs.setString('user_email', user.email);
|
|
} catch (e) {
|
|
state = state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: e.toString(),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|