Biometric login in flutter

Flutter Junction
CodeX
Published in
5 min readJun 22, 2022

In this article, we’ll be discussing on how the biometric authentication like TOUCH ID or PIN can be implemented in the flutter applications.

For getting our desired output, we’ll be using a package called local_auth. This package provides us means to perform on local, on-device authentication of users. With the help of this package, we will implement biometric authentication in our Flutter applications.

What is Biometric authentication?

Biometric verification is any means by which a person can be uniquely identified by evaluating one or more distinguishing biological traits such as facial characteristics, voice recognition, finger prints etc.

Let’s Dive In

Our application will consists of two screens, one is LoginScreen and other is SuccessScreen. In Login Screen, we will authenticate the user and the SuccessScreen is visible only when there is successful authentication.

local_auth package overview

Some of the primary features provided by the local_auth package are:

  • Check the compatibility of the device
  • List the types of biometric supported
  • Authentication using biometric or PIN

Lets discuss more about these features

Check the compatibility of the device

We are able to test whether the mobile phone supports the biometric authentication. For achieving this features, we’ll use isDeviceSupported method provided by the package local_auth.

//initialize the LocalAuthentication plugin
final LocalAuthentication auth = LocalAuthentication();
//check if the device supports the biometric authentication
bool isBioSupported=await auth.isDeviceSupported();

isDeviceSupported is an async method which returns a bool, defining whether the biometrics authentication is supported on the user’s device.

List the types of biometric supported

The getAvailableBiometrics method provided by the local_auth plugin can be used to retrieve a list of biometric types supported by the user’s device.

List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();

The biometrics types supported by the local_auth packages are:

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

Authentication using biometric or PIN

We have authenticate method provided the local_auth plugin, so as to authenticate users using biometrics or PIN.

bool isAuthenticated=auth.authenticate(
localizedReason: 'Complete the biometrics to continue',
options: const AuthenticationOptions(
biometricOnly: true,
useErrorDialogs: false,
stickyAuth: true,
),)

The method authenticate has options parameters that are applied to change some specific settings. This options paremeter takes AuthenticationOptions that takes some important parameters.

String localizedReason

It is used to show the message while prompting them for authentication.

Note: The highlighted message is localizedReason

bool biometricOnly

It can be either true or false.

When it is set to true, the non-biometric local authentication such as PIN and passcode are disabled.

And when it is set to false, the option for “Use pattern” or Use PIN” options are visible as shown in the image below.

bool useErrorDialogs

When this parameter is set to true, the plugin checks to see whether a user fingerprint record exists on the device. If no fingerprint is registered, the plugin will attempt to direct the user to the settings to create one.

stickyAuth

Under normal circumstances, the authentication process is terminated when the app is minimized or moved to the background. If stickyAuth is set to true, the authentication process is resumed when the app is brought back into focus.

Implementing biometric login

For that first we need to add local_auth package in the pubsec.yaml file.

local_auth: ^2.1.0

Then we first check if the biometric login is supported in the device or not. If it is supported we limit user to only login using biometric and after successful authentication, we grant the user access the success screen.

For that, create a new file named authservice.dart . Inside this file paste the code.

In the code above, we created a class named AuthService and defined a method authenticateUser. This method handles all the authentication logic and returns a bool representing if the biometric authentication was sucessful or not.

Now, in the LoginPage, we have to call the authenticateUser method when clicking the button as in the snipped below.

InkWell(onTap: () async {bool isAuthenticated = await AuthService.authenticateUser();
if (isAuthenticated) {
// ignore: use_build_context_synchronously
Navigator.push(context,
MaterialPageRoute(builder: (context) =>const SuccessScreen()),
);
} else {
// ignore: use_build_context_synchronouslyScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Authentication failed.'),),);}
},
child: Center( child: Container(
height: 60,
width: MediaQuery.of(context).size.width ,
decoration: BoxDecoration(border: Border.all(color: Colors.blueAccent, width: 2.5)),
child: Row(mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(Icons.fingerprint,color: Colors.blueAccent,),
Text("Login with BioMetrics",style: TextStyle(color: Colors.blueAccent),
)
],
)), ),
),

From the above snippet code, if the authentication is successful- we navigate to the SuccessScreen else we show the SnackBar with failed message.

Full LoginPage Code

Success Screen Code

Main.dart

App Permissions Settings

For Android

In the AndroidManifest.xml file, we have to add the USE_FINGERPRINT permission. AndroidManifest.xml file is located in android/src/main:

<manifest>  
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<application></application>
</manifest>

Then, update the MainActivity.kt file to use FlutterFragmentActivity instead of FlutterActivity:

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.embedding.engine.FlutterEngine
class MainActivity: FlutterFragmentActivity() {override fun configureFlutterEngine(@NonNull flutterEngine:FlutterEngine) {GeneratedPluginRegistrant.registerWith(flutterEngine)}
}

For iOS

For FaceID to work on iOS, add the following line to the Info.plist file. This defines the message that tells the user why the app is seeking permission to authenticate with Face ID.

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

Let’s get connected

We can be friends. Find on Facebook, Linkedin, Github, Youtube, BuyMeACoffee, and Instagram.

Visit: Flutter Junction

Contribute: BuyMeACoffee

Conclusion

I hope this article is helpful to you and you learned new things. I have used various things in this article that might be new for some of you.

If you learned something new or want to suggest something then please let me know in the comment.

If you loved the article click on 👏 icon which provides motivation on delivering you all with the new things.

Also follow to get updated on exciting articles and projects.

Learning by sharing gives great impact in learning process and making the community bigger and bigger.

Sharing is a magnet that attracts other enthusiast towards you.

Hence, lets take a small step on making our learning community bigger.

Share this article with your friends or tweet about this article if you loved it.

Get full at:

Thank you for reading!!!

--

--

Flutter Junction
CodeX
Writer for

Flutter Junction is a comprehensive learning platform offering a wealth of resources for developers of all experience levels.