Flutterexperts

Empowering Vision with FlutterExperts' Expertise
BioMetric Authentication In Flutter Application

Hello Everyone! today my writing a blog about security or we can say privacy. In this blog, we learn how to add fingerprint authentication to our flutter application in a very easy way. As a developer, I think bio-metrics is very safe. In this blog, we learn how to implement BioMetric Authentication in Flutter Application.

For BioMetric Authentication, we need our local database by which we can check the fingerprint.

We use many types of bio-metric :

  • BiometricType.face
  • BiometricType.fingerprint
  • BiometricType.weak
  • BiometricType.strong

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents:

Implementation

Conclusion

GitHub Link


Implementation:

First, we have to create a new For BioMetric Authentication first we need to add dependencies in pubspec. ymal which is local_auth.dependencies:
local_auth: ^1.1.10

|> local_auth: This Flutter plugin gives the means to perform local, on-device user authentication. Import the following file into your StatefulWidget class.

import 'package:local_auth/local_auth.dart';

This includes authentication with biometrics such as fingerprint or facial recognition on supported devices. It supports Android, IOS, and Windows. For local_auth we have to check the capabilities of the device.


>Device capabilities: If we want to use Fingerprint Authentication we have to check the capability of our device for check the capability, we should call canCheckBiometrics()or isDeviceSupport()

import 'package:local_auth/local_auth.dart';
final LocalAuthentication auth = LocalAuthentication();
final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics;
final bool canAuthenticate = canAuthenticateWithBiometrics || await auth.isDeviceSupported();

canCheckBiometric() only designate whether hardware support is available, not whether the device has any biometrics enrolled. To get a list of enrolled biometrics, call getAvailableBiometrics().

This plugin will build and run on SDK 16+, but isDeviceSupported()will always return false before SDK 23.


> Dialogs:

The plugin provides default dialog’s for the following cases:

  1. Passcode/PIN/Pattern Not Set: The user has not yet configured a passcode on iOS or a PIN/pattern on Android.
  2. Bio-metrics Not Enrolled: The user has not enrolled in any biometrics on the device.
import 'package:local_auth/error_codes.dart' as auth_error;
try {
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
options: const AuthenticationOptions(useErrorDialogs: false));
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
// Add handling of no hardware here.
} else if (e.code == auth_error.notEnrolled) {
} else {}
}

If you want to edit dialog, so you can pass AuthMessages for each platform in which you want to edit the message.

import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
authMessages: const <AuthMessages>[
AndroidAuthMessages(
signInTitle: 'Oops! Biometric authentication required!',
cancelButton: 'No thanks',
),
IOSAuthMessages(
cancelButton: 'No thanks',
),
]);

>IOS Integration:

You need to add these lines in Info. plist file. Failure to do so results in a dialog that tells the user your app has not been updated to use Face ID.

<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>

>Android Integration:

  • If you are using FlutterActivity directly, change it to FlutterFragmentActivity in your AndroidManifest.xml.
  • If you are using a custom activity, update your MainActivity.java
import io.flutter.embedding.android.FlutterFragmentActivity;
public class MainActivity extends FlutterFragmentActivity {
}

or MainActivity.

import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity: FlutterFragmentActivity() {
}

we also permit using local_auth, add these lines in AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<manifest>

To check if local authentication is available on this device.

Future<void> _checkBiometric() async {
bool canCheckBiometric = false;

try {
canCheckBiometric = await auth.canCheckBiometrics;
} on PlatformException catch (e) {
print(e);
}

if (!mounted) return;
setState(() {
_canCheckBiometric = canCheckBiometric;
}
);
}

We create a final variable with the name auth in which we pass LocalAuthentication().

final auth = LocalAuthentication();

To get the list of enrolled biometrics on this device we create a list which is biometricType.

Future _getAvailableBiometric() async {
List<BiometricType> availableBiometric = [];

try {
availableBiometric = await auth.getAvailableBiometrics();
} on PlatformException catch (e) {
print(e);
}

setState(() {
_availableBiometric = availableBiometric;
});
}

Also create a String variable to inspect the biometric, whether it’s successful or unsuccessful. Then we create a method, and in the starting, we pass authenticated as false. and after that, we define authentication with biometrics.

And use the parameters of it, localizedReason in which we define the string, set useErrorDialogs as true, and also set stickyAuth as true. in this method, we also check whether the bio-metric is authenticated or not.

Future<void> _authenticate() async {
bool authenticated = false;
try {
authenticated = await auth.authenticateWithBiometrics(
localizedReason: "Scan your finger to authenticate",
useErrorDialogs: true,
stickyAuth: true);
} on PlatformException catch (e) {
print(e);
}
setState(() {
authorized =
authenticated ? "Authorized success" : "Failed to authenticate";
print(authorized);
});
}

After creating all these methods, call these methods to initState().

@override
void initState() {
_checkBiometric();
_getAvailableBiometric();

super.initState();
}

Let’s come to UI part, In UI part return the scaffold in buildContext. add gave the background color of the Screen. In the body of the Scaffold pass Column(), take text as children,

and pass Login text. Create a FloatingActionButton and pass _authenticate at onPressed.

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey.shade600,
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Center(
child: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontSize: 48.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 50.0),
child: Column(
children: [
Container(
margin: const EdgeInsets.symmetric(
vertical: 15.0),
child: const Text(
"Authenticate using your fingerprint instead of
your password",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white,
height: 1.5),
),
),
Container(
margin: const EdgeInsets.symmetric(
vertical: 15.0),
width: double.infinity,
child: FloatingActionButton(
onPressed: _authenticate,
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
child: const Padding(
padding: EdgeInsets.symmetric(
horizontal: 24.0, vertical: 14.0),
child: Text(
"Authenticate",
style: TextStyle(color: Colors.white),
),
),
),
)
],
),
)
],
),
),
);
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Conclusion:-

In this article, we have been through why Bio-metric is important and how to implement this in any Flutter Project. And also learn the importance of local_auth and how many types of Bio-metric are in this package.

❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

Find the source code of the Fingerprint Authentication In Flutter Application :

GitHub – flutter-devs/biometric_authentication_flutter
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.