Skip to content

Kotlin Codes

  • Home
  • Flutter
  • Kotlin
  • SwiftUI
  • About Me
  • Home
    • Blog
    • Privacy Policy
  • Flutter
    • Widgets In Flutter
      • Cupertino Widgets
      • iOS Styling Flutter
    • Database & Storage
    • State Management in Flutter
    • Performance Optimization
    • Networking & APIs
    • Testing & Debugging
  • Kotlin
    • Kotlin XML Development(Traditional View-based UI)
      • Introduction to XML UI Development
      • State Management and Architecture
      • Advanced Topics
      • Firebase and Cloud Integration
      • UI Components and Customization
      • Media and Visual Enhancements
      • Navigation and Data Handling
      • UI Performance Optimization
      • Networking and Data Management
    • Jetpack Compose
      • UI Elements
      • Kotlin Multiplatform
      • Accessibility
      • Animation
      • Core Concepts
      • Custom Drawing
      • Interoperability
      • Layouts
      • State Management
      • Modifiers
      • Navigation
      • Testing
      • Theming
      • Performance
    • Kotin-CodeChallenge
  • SwiftUI
  • About Me

Implementing Biometric Authentication in Flutter

March 2, 2025May 15, 2025 Sayandh

Biometric authentication is a modern security feature that enhances user experience by allowing users to authenticate using their biological characteristics such as fingerprint, face, or iris scan. Implementing biometric authentication in Flutter applications can significantly improve security while providing a seamless login experience.

What is Biometric Authentication?

Biometric authentication uses unique biological traits to verify a user’s identity. It is considered more secure than traditional password-based authentication since biometrics are difficult to replicate or steal.

Why Use Biometric Authentication in Flutter?

  • Enhanced Security: Adds a layer of security that is difficult to compromise.
  • Improved User Experience: Provides a quick and easy way for users to authenticate.
  • Modern Authentication Method: Aligns with contemporary security standards.

How to Implement Biometric Authentication in Flutter

To implement biometric authentication in Flutter, we use the local_auth package, which provides the necessary functionalities to access the device’s biometric features.

Step 1: Add the local_auth Dependency

Add the local_auth package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^2.1.7

After adding the dependency, run flutter pub get in your terminal.

Step 2: Configure Native Platforms

For Android and iOS, some platform-specific configurations are needed.

Android Configuration

Modify your android/app/build.gradle file. Set the minSdkVersion to 23 or higher and add BiometricPrompt.AUTHENTICATE_WEAK in the keyguardManager line. Without that Android emulator (api < 30) can be unstable.

android {
    compileSdkVersion 33

    defaultConfig {
        applicationId "your_application_id"
        minSdkVersion 23
        targetSdkVersion 33
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    ...
}

Add the following permission to your AndroidManifest.xml file (located in android/app/src/main):


iOS Configuration

Add the following entry to your Info.plist file (located in ios/Runner):

NSFaceIDUsageDescription
Why is my app authenticating using face id?

This key describes why your app wants to use Face ID. The string will be displayed to the user when Face ID is requested for the first time. If you plan on supporting iOS versions prior to 11.0 then also add:

Privacy - Face ID Usage Description
Why is my app authenticating using face id?

Step 3: Implement Biometric Authentication Logic

Now, let’s implement the Dart code for biometric authentication.

import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Biometric Authentication Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BiometricAuthScreen(),
    );
  }
}

class BiometricAuthScreen extends StatefulWidget {
  @override
  _BiometricAuthScreenState createState() => _BiometricAuthScreenState();
}

class _BiometricAuthScreenState extends State {
  final LocalAuthentication auth = LocalAuthentication();
  bool _canCheckBiometrics = false;
  String _authorized = 'Not Authorized';

  @override
  void initState() {
    super.initState();
    _checkBiometrics();
  }

  Future _checkBiometrics() async {
    bool canCheck = false;
    try {
      canCheck = await auth.canCheckBiometrics;
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _canCheckBiometrics = canCheck;
    });
  }

  Future _authenticate() async {
    bool authenticated = false;
    try {
      setState(() {
        _authorized = 'Authenticating';
      });
      authenticated = await auth.authenticate(
        localizedReason: 'Scan your fingerprint to authenticate',
        options: const AuthenticationOptions(
          stickyAuth: true,
        ),
      );
      setState(() {
        _authorized = authenticated ? 'Authorized' : 'Not Authorized';
      });
    } on PlatformException catch (e) {
      print(e);
      setState(() {
        _authorized = 'Error - ${e.message}';
      });
      return;
    }
    if (!mounted) return;

    final String message = authenticated ? 'Authorized' : 'Not Authorized';
    print(message);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Biometric Authentication'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Can check biometrics: $_canCheckBiometricsn'),
            Text('Current State: $_authorizedn'),
            ElevatedButton(
              onPressed: _authenticate,
              child: Text('Authenticate'),
            ),
          ],
        ),
      ),
    );
  }
}

Explanation:

  • We initialize LocalAuthentication and define necessary variables to hold the state of biometric checks.
  • The _checkBiometrics method checks if the device supports biometric authentication.
  • The _authenticate method triggers the biometric authentication process using auth.authenticate.
  • The UI displays the current authentication status and provides a button to trigger authentication.

Explanation of Code

  • Import Statements:
  • import 'package:flutter/material.dart';: Imports the necessary Flutter widgets.
  • import 'package:local_auth/local_auth.dart';: Imports the local_auth plugin.
  • import 'package:flutter/services.dart';: Provides access to platform-specific services.
  • MyApp Class:
  • Sets up the basic MaterialApp.
  • The home is set to BiometricAuthScreen, which is where the main logic resides.
  • BiometricAuthScreen Class:
  • This StatefulWidget class creates a simple screen for biometric authentication.
  • _BiometricAuthScreenState Class:
  • Variables:

    • final LocalAuthentication auth = LocalAuthentication();: Initializes an instance of LocalAuthentication.
    • bool _canCheckBiometrics = false;: A boolean to store whether the device can check biometrics.
    • String _authorized = 'Not Authorized';: A string to store the authentication state.
  • initState Method:

    • Calls _checkBiometrics() when the widget is initialized.
  • _checkBiometrics Method:
  • Asynchronously checks if the device can perform biometric authentication.
  • It sets _canCheckBiometrics to true or false based on the check.
  • Error Handling: Catches platform exceptions in case the check fails.
  • _authenticate Method:
  • Asynchronously authenticates the user using biometrics.
  • Updates the UI state:
    • Sets _authorized to ‘Authenticating’ before starting.
    • If authentication succeeds, sets _authorized to ‘Authorized’.
    • If authentication fails, sets _authorized to ‘Not Authorized’.
  • Configuration:
    • Calls auth.authenticate with the message ‘Scan your fingerprint to authenticate’.
    • Uses AuthenticationOptions to specify stickyAuth: true, which keeps the authentication session active.
  • Error Handling:
    • Handles platform exceptions if authentication fails.
    • Sets _authorized to an error message.
  • Logging:
    • Prints the authentication message to the console.
  • build Method:
  • Builds the UI for the authentication screen.
  • Displayes Text widgets:
    • Shows if the device can check biometrics (_canCheckBiometrics).
    • Shows the current authentication state (_authorized).
  • Button Widget: Creates an ElevatedButton that triggers the _authenticate() method when pressed.

Conclusion

Implementing biometric authentication in Flutter applications enhances security and improves user experience. The local_auth package simplifies the process, providing a secure and modern authentication method. Follow these steps to integrate biometric authentication seamlessly into your Flutter apps, ensuring a secure and user-friendly login experience.

Beyond This Article: Your Next Discovery Awaits

Mastering REST API Integration Best Practices (Error Handling, Caching, Authentication) in Flutter
Firebase Authentication Integration with XML UI
Encrypting Local Storage in Flutter with Hive
Implementing In-App Updates for Flutter Applications
Integrating with Microsoft Azure Services in Flutter
Using Environment Variables in Flutter Apps
Tagged with Biometric Login Flutter, Dart Biometrics, Face ID Flutter, Fingerprint Auth Flutter, Flutter Authentication Example, Flutter Biometric Authentication, Flutter Mobile Security, Flutter Security, Local Authentication Flutter, Secure Flutter Apps
  • Flutter

Post navigation

Previous Post

SwiftUI Alert, ActionSheet, and Confirmation Dialogs

Next Post

Building Custom SwiftUI Shapes with Path and Shape

Recents

  • Writing Effective Unit Tests for Individual Widgets and UI Components to Ensure They Function Correctly in Isolation in Flutter
  • Understanding the Architecture and Platform Differences When Developing Flutter Desktop Applications
  • Using Firebase Analytics to Track User Behavior, Screen Views, Custom Events, and User Properties in Flutter
  • Using the web_socket_channel Package to Establish and Manage WebSocket Connections in Flutter
  • Working with WebSockets to Enable Real-Time, Bidirectional Communication Between Your Flutter App and a Backend Server
  • Dart
  • Flutter
    • Advanced Concepts
    • Animations & UI Enhancements
    • Data Handling (JSON, REST APIs, Databases)
    • Database & Storage
    • Input Widgets
    • iOS Styling Flutter
    • Layout Widgets
    • Navigation and Routing
    • Networking & APIs
    • Performance Optimization
    • Platform Integration (Native Features)
    • State Management (Provider, BLoC, Riverpod)
    • State Management in Flutter
    • Testing (Unit, Widget, Integration)
    • Testing & Debugging
    • UI Basics
    • Widgets In Flutter
      • Cupertino Widgets
  • Kotlin
    • Jetpack Compose
      • Accessibility
      • Animation
      • Core Concepts
      • Custom Drawing
      • Interoperability
      • Kotlin Multiplatform
      • Layouts
      • Modifiers
      • Navigation
      • Performance
      • State Management
      • Testing
      • Theming
      • UI Elements
    • Kotin-CodeChallenge
    • Kotlin XML Development(Traditional View-based UI)
      • Accessibility
      • Advanced Topics
      • Advanced Topics & Custom Views
      • Animation
      • Data Binding
      • Drawables
      • Firebase and Cloud Integration
      • Introduction to XML UI Development
      • Kotlin Integration & Patterns
      • Layouts
      • Media and Visual Enhancements
      • Navigation and Data Handling
      • Networking and Data Management
      • RecyclerView
      • State Management and Architecture
      • Styles & Themes
      • UI Components and Customization
      • UI Performance Optimization
      • View Binding
      • Views
      • XML Techniques
  • SwiftUI

© KotlinCodes. Explore the latest Kotlin tutorials, Flutter guides, and Dart programming tips. | Learn Kotlin | Flutter Development | Dart Programming | Flutter Widgets