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

April 2, 2025May 15, 2025 Sayandh

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_auth and flutter/services.dart.
  • LocalAuthentication Instance: Creates an instance of LocalAuthentication for 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.
  • _checkBiometrics Function: Checks if the device can perform biometric authentication.
  • _authenticate Function: Initiates the authentication process using biometrics.
  • build Method: 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.

Beyond This Article: Your Next Discovery Awaits

Implementing Data Encryption in Flutter
Integrating with Microsoft Azure Services in Flutter
Implementing Password Visibility Toggles in Flutter
Implementing In-App Updates for Flutter Applications
Analyzing Your Flutter Code with Static Analysis Tools to Identify Potential Issues
Implementing Secure Data Storage on Devices in Flutter
Tagged with Biometric Login Flutter, Face ID Flutter, Fingerprint Authentication Flutter, Flutter Authentication Tutorial, Flutter Biometric Authentication, Flutter Plugin Integration, Flutter Security, Flutter Security Best Practices, Local Auth Plugin, Secure Flutter Apps
  • Advanced Concepts

Post navigation

Previous Post

Lambda Modifiers for Performance: Jetpack Compose Optimization Guide

Next Post

Implementing Cross-Field Validation in Forms in Flutter

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