Skip to content

Instantly share code, notes, and snippets.

@YousefMohamed6
Created April 17, 2025 19:44
Show Gist options
  • Save YousefMohamed6/a2f5a9e86648478dae34304fd784e8a2 to your computer and use it in GitHub Desktop.
Save YousefMohamed6/a2f5a9e86648478dae34304fd784e8a2 to your computer and use it in GitHub Desktop.
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
class LocalAuthService {
LocalAuthService() {
_init();
}
final LocalAuthentication _localAuth = LocalAuthentication();
bool _isSupported = false;
bool get isSupported => _isSupported;
bool _isAuthenticating = false;
bool get isAuthenticating => _isAuthenticating;
bool _authenticated = false;
bool get authenticated => _authenticated;
bool _canCheckBiometrics = false;
bool get canCheckBiometrics => _canCheckBiometrics;
List<BiometricType> _availableBiometrics = [];
List<BiometricType> get availableBiometrics => _availableBiometrics;
Future<void> _init() async {
await checkDeviceSupported();
await checkBiometrics();
}
Future<void> checkDeviceSupported() async {
try {
_isSupported = await _localAuth.isDeviceSupported();
} on PlatformException catch (_) {
_isSupported = false;
}
}
Future<void> checkBiometrics() async {
if (isSupported) {
_canCheckBiometrics = await _localAuth.canCheckBiometrics;
}
}
Future<void> getAvailableBiometrics() async {
if (canCheckBiometrics) {
_availableBiometrics = await _localAuth.getAvailableBiometrics();
}
}
Future<void> authenticate({required String reason}) async {
if (!isSupported) return;
_isAuthenticating = true;
_authenticated = await _localAuth.authenticate(
localizedReason: reason,
options: const AuthenticationOptions(stickyAuth: true),
);
_isAuthenticating = false;
}
Future<void> cancelAuthentication() async {
await _localAuth.stopAuthentication();
_isAuthenticating = false;
}
Future<void> authenticateWithBiometrics({required String reason}) async {
if (!isSupported) return;
if (!canCheckBiometrics) return;
_isAuthenticating = true;
_authenticated = await _localAuth.authenticate(
localizedReason: reason,
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
_isAuthenticating = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment