add flutter
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:ontime_merchant_flutter/data/api/api_client.dart';
|
||||
import 'package:ontime_merchant_flutter/features/auth/data/merchant_auth_api.dart';
|
||||
import 'package:ontime_merchant_flutter/features/auth/data/models/merchant_model.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class AuthState {
|
||||
const AuthState({
|
||||
this.merchant,
|
||||
this.isLoading = false,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
final MerchantModel? merchant;
|
||||
final bool isLoading;
|
||||
final String? errorMessage;
|
||||
|
||||
AuthState copyWith({
|
||||
MerchantModel? merchant,
|
||||
bool? isLoading,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return AuthState(
|
||||
merchant: merchant ?? this.merchant,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
errorMessage: errorMessage,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final authControllerProvider =
|
||||
StateNotifierProvider<AuthController, AuthState>((ref) => AuthController());
|
||||
|
||||
class AuthController extends StateNotifier<AuthState> {
|
||||
AuthController() : super(const AuthState());
|
||||
|
||||
late final MerchantAuthApi _api =
|
||||
MerchantAuthApi(ApiClient(basicAuthUser: null, basicAuthPassword: null));
|
||||
|
||||
Future<void> login({
|
||||
required String noTelepon,
|
||||
required String password,
|
||||
String? fcmToken,
|
||||
}) async {
|
||||
state = state.copyWith(isLoading: true, errorMessage: null);
|
||||
try {
|
||||
final merchant = await _api.login(
|
||||
noTelepon: noTelepon,
|
||||
password: password,
|
||||
fcmToken: fcmToken,
|
||||
);
|
||||
state = state.copyWith(merchant: merchant, isLoading: false);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('merchant_id_mitra', merchant.idMitra);
|
||||
await prefs.setString('merchant_id_merchant', merchant.idMerchant);
|
||||
await prefs.setString('merchant_phone', merchant.teleponMitra);
|
||||
await prefs.setString('merchant_token', merchant.tokenMerchant);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
errorMessage: e.toString().replaceFirst('Exception: ', ''),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void logout() {
|
||||
state = const AuthState();
|
||||
}
|
||||
|
||||
static Future<void> clearStored() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove('merchant_id_mitra');
|
||||
await prefs.remove('merchant_id_merchant');
|
||||
await prefs.remove('merchant_phone');
|
||||
await prefs.remove('merchant_token');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user