In today’s mobile applications, security is paramount. Biometric authentication offers a secure and user-friendly way to authenticate users. Flutter, Google’s UI toolkit, provides a straightforward way to implement biometric authentication using plugins. This article walks you through the steps to implement biometric authentication in a Flutter application.
What is Biometric Authentication?
Biometric authentication uses unique biological traits, such as fingerprints or facial recognition, to verify a user’s identity. It is a secure alternative to traditional password or PIN-based authentication methods.
Why Use Biometric Authentication?
- Enhanced Security: Biometric data is unique and difficult to replicate.
- User Convenience: It’s faster and more convenient than typing passwords.
- Improved User Experience: Provides a seamless and secure login experience.
How to Implement Biometric Authentication in Flutter
To implement biometric authentication in Flutter, we’ll use the local_auth plugin. This plugin provides a platform-agnostic way to access biometric authentication APIs on both Android and iOS.
Step 1: Add the local_auth Plugin
First, add the local_auth plugin to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
local_auth: ^2.1.6
After adding the dependency, run flutter pub get to install the plugin.
Step 2: Configure Native Platforms
Depending on the platforms you are targeting, you may need to configure the native projects.
iOS Configuration
For iOS, add the following keys to your Info.plist file to explain why your app needs to use biometrics:
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
Android Configuration
For Android, add the USE_BIOMETRIC permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
Step 3: Implement Biometric Authentication in Flutter
Now, let’s implement the biometric authentication logic in a Flutter widget:
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:flutter/services.dart';
class BiometricAuth extends StatefulWidget {
@override
_BiometricAuthState createState() => _BiometricAuthState();
}
class _BiometricAuthState extends State<BiometricAuth> {
final LocalAuthentication auth = LocalAuthentication();
bool _canCheckBiometrics = false;
String _authorized = 'Not Authorized';
Future<void> _checkBiometrics() async {
bool canCheck = false;
try {
canCheck = await auth.canCheckBiometrics;
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_canCheckBiometrics = canCheck;
});
}
Future<void> _authenticate() async {
bool authenticated = false;
try {
authenticated = await auth.authenticate(
localizedReason: 'Scan your fingerprint to authenticate',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
print("Authenticated : $authenticated");
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_authorized = authenticated ? 'Authorized' : 'Not Authorized';
});
}
@override
void initState() {
super.initState();
_checkBiometrics();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Biometric Authentication'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Can check biometrics: $_canCheckBiometricsn'),
Text('Current State: $_authorizedn'),
ElevatedButton(
onPressed: _authenticate,
child: const Text('Authenticate'),
),
],
),
),
);
}
}
Here’s a breakdown of the code:
- Import Statements: Imports necessary packages, including
local_authandflutter/services.dart. LocalAuthenticationInstance: Creates an instance ofLocalAuthenticationfor handling biometric operations.- State Variables:
_canCheckBiometrics: A boolean indicating whether biometric authentication is available on the device._authorized: A string showing the current authorization state.
_checkBiometricsFunction: Checks if the device can perform biometric authentication._authenticateFunction: Initiates the authentication process using biometrics.buildMethod: Builds the UI with buttons to check and initiate biometric authentication.
Step 4: Integrating the Widget into Your App
Add the BiometricAuth widget to your main app:
import 'package:flutter/material.dart';
import 'biometric_auth.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Biometric Authentication',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BiometricAuth(),
);
}
}
Conclusion
Biometric authentication enhances the security and user experience of your Flutter applications. By using the local_auth plugin, you can easily integrate biometric authentication, making your app more secure and user-friendly. This article provided a comprehensive guide to implementing biometric authentication in Flutter, including setup, configuration, and implementation steps.