Files
Tanami_App/lib/features/biometric/presentation/bloc/biometric_bloc.dart
2024-07-09 14:56:23 +05:30

58 lines
1.8 KiB
Dart

import 'dart:io';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:local_auth/local_auth.dart';
import 'biometric_event.dart';
import 'biometric_state.dart';
class BiometricBloc extends Bloc<BiometricEvent, BiometricState> {
final LocalAuthentication localAuthentication;
BiometricBloc(this.localAuthentication) : super(BiometricInitial()) {
on<CheckBiometricEvent>(_onCheckBiometric);
on<AuthenticateBiometricEvent>(_onAuthenticateBiometric);
}
Future<void> _onCheckBiometric(
CheckBiometricEvent event, Emitter<BiometricState> emit) async {
emit(BiometricChecking());
bool canAuthenticate = await localAuthentication.canCheckBiometrics;
emit(BiometricChecked(canAuthenticate));
}
Future<void> _onAuthenticateBiometric(
AuthenticateBiometricEvent event, Emitter<BiometricState> emit) async {
emit(BiometricAuthenticating());
try {
bool authenticated = false;
if (Platform.isIOS) {
authenticated = await localAuthentication.authenticate(
localizedReason: 'Please authenticate to access the app',
options: const AuthenticationOptions(
useErrorDialogs: true,
stickyAuth: true,
biometricOnly: true,
),
);
} else if (Platform.isAndroid) {
authenticated = await localAuthentication.authenticate(
localizedReason: 'Please authenticate to access the app',
options: const AuthenticationOptions(
useErrorDialogs: true,
stickyAuth: true,
),
);
}
if (authenticated) {
emit(BiometricAuthenticated());
} else {
emit(BiometricFailed('Authentication failed'));
}
} catch (e) {
emit(BiometricFailed(e.toString()));
}
}
}