Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Authenticate with Pin, Pattern, Face/Fingerprint Biometric Scan in Flutter App

In this example, we are going to show you the easiest way to authenticate identity of user using biometrics like Fingerprint and Face scan. Besides that, you will learn to authenticate with pattern pass, pin and passcode of the lock system security. See the example below:

First, you need to add local_auth Flutter package in your project by adding following lines on pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^1.1.8

For Android Platform Configuration:

Add USE_FINGERPRINT permission on AndroidManifest.xml file

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

If your project is using JAVA environment for Android then update MainActivity.java

import android.os.Bundle;
import io.flutter.app.FlutterFragmentActivity;
import io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin;
import io.flutter.plugins.localauth.LocalAuthPlugin;

public class MainActivity extends FlutterFragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FlutterAndroidLifecyclePlugin.registerWith(
                registrarFor(
                        "io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin"));
        LocalAuthPlugin.registerWith(registrarFor("io.flutter.plugins.localauth.LocalAuthPlugin"));
    }
}

NOTE: Be careful not to replace, topmost package line like package com.testapp.flutter.testapp us.

OR, if you are using Kotlin Environment then Update MainActivity.kt 

import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}

NOTE: Be Careful not to replace your package line like mentioned above.

For iOS Configuration:

Add the following line on info.plist:

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

Now, Flutter Part:

How to Check if system has Biometric Scanner like Face/Fingerprint Scanner:

 bool hasbiometrics = await auth.canCheckBiometrics;

How to Check if Face Scan is available on System:

List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();
//returns list of biometrics

if (availableBiometrics.contains(BiometricType.face)) {
     print("Face scan is available");
}else{
    print("Face scan is not available");
}

Note: It will return false, if there is no face security added on security even if face scan is on the system.

How to Check if Fingerprint Scan is available on System:

List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();
//returns list of biometrics

if (availableBiometrics.contains(BiometricType.fingerprint)) {
     print("Finger print scan is available");
}else{
    print("Finger print scan is not available");
}

Note: It will return false, if there is no finger pirnt added on security.

How to open Biometric Scanner for Authentication:

bool pass = await auth.authenticate(
       localizedReason: 'Authenticate with fingerprint/face',
       biometricOnly: true
 );

biometricOnly:true, will force to open biometric scanner during authentication. It will return true, if authentication is successful.

Note: It will show, the biometric scanner according to the availability of scanner and priority.

How to open pin/pattern/passcode input for Authentication:

bool pass = await auth.authenticate(
           localizedReason: 'Authenticate with pattern/pin/passcode',
           biometricOnly: false
);

If there is biometric, it will show biometric scanner, otherwise, it will show available authentication security pass.

Full Dard Code Example:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
void main() {
  runApp(
    MaterialApp(
      home: MyApp(),
    )
  );
}

class MyApp extends StatefulWidget{
  
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final LocalAuthentication auth = LocalAuthentication();

  String msg = "You are not authorized.";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Fingerprint/Face Scan/Pin/Pattern Authenciation"),
              backgroundColor: Colors.purple,
          ),
          body: Container( 
              margin: EdgeInsets.only(top:50),
              alignment: Alignment.center,
              child: Column(
                children: [
                    Center( 
                       child: Text(msg),
                    ),
                    Divider(),
                    ElevatedButton(
                      onPressed:() async {
                        try {
                              bool hasbiometrics = await auth.canCheckBiometrics; //check if there is authencations, 
                              
                              if(hasbiometrics){
                                      List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();
                                      if (Platform.isIOS) {
                                            if (availableBiometrics.contains(BiometricType.face)) {
                                                  
                                                      bool pass = await auth.authenticate(
                                                        localizedReason: 'Authenticate with fingerprint',
                                                        biometricOnly: true  );

                                                      if(pass){
                                                            msg = "You are Autenciated.";
                                                            setState(() {
                                                                
                                                            });
                                                      }
                                                
                                            }
                                        }else{
                                            if (availableBiometrics.contains(BiometricType.fingerprint)) {
                                                bool pass = await auth.authenticate(
                                                        localizedReason: 'Authenticate with fingerprint/face',
                                                        biometricOnly: true );
                                                if(pass){
                                                    msg = "You are Authenicated.";
                                                    setState(() {
                                                      
                                                    });
                                                }
                                            }
                                        }
                              }else{
                                  msg = "You are not alowed to access biometrics.";
                              }

                              
                         } on PlatformException catch (e) {
                             msg = "Error while opening fingerprint/face scanner";
                        }
                       
                      }, 
                      child: Text("Authenticate with Fingerprint/Face Scan")
                    ),


                    ElevatedButton(
                      onPressed:() async {
                        try {       
                                  
                              bool pass = await auth.authenticate(
                                      localizedReason: 'Authenticate with pattern/pin/passcode',
                                      biometricOnly: false );
                              if(pass){
                                  msg = "You are Authenticated.";
                                  setState(() {
                                    
                                  });
                              }
                                      
                         } on PlatformException catch (e) {
                             msg = "Error while opening fingerprint/face scanner";
                        }
                       
                      }, 
                      child: Text("Authenticate with Pin/Passcode/Pattern Scan")
                    ),
                ],

              ),     
          )
      );
  }
}

Don't forget to configure MainActitivty, AndroidManifist.xml on Android and info.plist on iOS as mentioned above.

Output Screenshot:

Widget Output Fingerprint Scanner popup on button click

In this way, you can authenticate using Biometrics like Finger print, face scan, and Pin, Passcode and Pattern lock in Flutter App.

No any Comments on this Article


Please Wait...