Bird
Raised Fist0
Fluttermobile~20 mins

Biometric authentication in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Biometric Login Screen
This screen allows users to log in using their fingerprint or face recognition if available on their device.
Target UI
-------------------------
|  Biometric Login      |
|-----------------------|
|                       |
|   [Fingerprint Icon]   |
|                       |
|  Tap to authenticate  |
|                       |
|  [Login with PIN]      |
-------------------------
Show a fingerprint icon centered on the screen
Display a message 'Tap to authenticate' below the icon
When user taps the fingerprint icon, start biometric authentication
If authentication succeeds, show a success message
If authentication fails or is not available, show an error message
Provide a button 'Login with PIN' below to fallback to PIN login
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';

class BiometricLoginScreen extends StatefulWidget {
  @override
  _BiometricLoginScreenState createState() => _BiometricLoginScreenState();
}

class _BiometricLoginScreenState extends State<BiometricLoginScreen> {
  final LocalAuthentication auth = LocalAuthentication();
  String _message = 'Tap to authenticate';

  // TODO: Add method to handle biometric authentication

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Biometric Login')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.fingerprint, size: 100, color: Colors.blue),
            SizedBox(height: 20),
            Text(_message, style: TextStyle(fontSize: 18)),
            SizedBox(height: 40),
            ElevatedButton(
              onPressed: () {
                // TODO: Add PIN login navigation
              },
              child: Text('Login with PIN'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';

class BiometricLoginScreen extends StatefulWidget {
  @override
  _BiometricLoginScreenState createState() => _BiometricLoginScreenState();
}

class _BiometricLoginScreenState extends State<BiometricLoginScreen> {
  final LocalAuthentication auth = LocalAuthentication();
  String _message = 'Tap to authenticate';

  Future<void> _authenticate() async {
    bool authenticated = false;
    try {
      authenticated = await auth.authenticate(
        localizedReason: 'Please authenticate to login',
        options: const AuthenticationOptions(
          biometricOnly: true,
          stickyAuth: true,
        ),
      );
    } catch (e) {
      setState(() {
        _message = 'Error: ${e.toString()}';
      });
      return;
    }

    setState(() {
      _message = authenticated ? 'Authentication successful!' : 'Authentication failed. Try again.';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Biometric Login')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: _authenticate,
              child: const Icon(Icons.fingerprint, size: 100, color: Colors.blue),
            ),
            const SizedBox(height: 20),
            Text(_message, style: const TextStyle(fontSize: 18)),
            const SizedBox(height: 40),
            ElevatedButton(
              onPressed: () {
                // Placeholder for PIN login navigation
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Navigate to PIN login screen')),
                );
              },
              child: const Text('Login with PIN'),
            ),
          ],
        ),
      ),
    );
  }
}

We use the local_auth package to access biometric features.

The _authenticate method tries to authenticate the user with biometrics only.

If authentication succeeds, we update the message to show success.

If it fails or an error occurs, we show an error message.

The fingerprint icon is wrapped in a GestureDetector so tapping it starts authentication.

The 'Login with PIN' button currently shows a message as a placeholder for navigation.

Final Result
Completed Screen
-------------------------
|  Biometric Login      |
|-----------------------|
|                       |
|   [Fingerprint Icon]   |
|                       |
| Authentication success |
|                       |
|  [Login with PIN]      |
-------------------------
User taps fingerprint icon to start biometric authentication
If successful, message changes to 'Authentication successful!'
If failed, message changes to 'Authentication failed. Try again.'
Tapping 'Login with PIN' shows a temporary message about navigation
Stretch Goal
Add a fallback to device passcode authentication if biometrics are not available or fail
💡 Hint
Use the 'authenticate' method without 'biometricOnly: true' option to allow device passcode fallback

Practice

(1/5)
1. What is the main purpose of biometric authentication in a Flutter app?
easy
A. To send notifications to users
B. To change the app's theme colors automatically
C. To speed up app loading times
D. To secure the app using fingerprint or face recognition

Solution

  1. Step 1: Understand biometric authentication

    Biometric authentication uses unique physical traits like fingerprint or face to secure access.
  2. Step 2: Identify its purpose in apps

    It protects sensitive data by allowing only authorized users to enter.
  3. Final Answer:

    To secure the app using fingerprint or face recognition -> Option D
  4. Quick Check:

    Biometric authentication = Secure app access [OK]
Hint: Biometrics means using your body to unlock [OK]
Common Mistakes:
  • Confusing biometric authentication with UI changes
  • Thinking it improves app speed
  • Assuming it sends notifications
2. Which Flutter package is commonly used to implement biometric authentication?
easy
A. local_auth
B. shared_preferences
C. provider
D. http

Solution

  1. Step 1: Recall Flutter packages for biometrics

    The local_auth package provides access to fingerprint and face authentication.
  2. Step 2: Compare with other packages

    http is for network calls, provider for state management, and shared_preferences for storing data.
  3. Final Answer:

    local_auth -> Option A
  4. Quick Check:

    Biometric package = local_auth [OK]
Hint: local_auth sounds like local device authentication [OK]
Common Mistakes:
  • Choosing http for biometrics
  • Confusing provider with authentication
  • Picking shared_preferences for biometrics
3. What will the following Flutter code print if biometric authentication is available and successful?
final isAvailable = await auth.canCheckBiometrics;
if (isAvailable) {
  final didAuthenticate = await auth.authenticate(
    localizedReason: 'Please authenticate',
  );
  print(didAuthenticate);
} else {
  print('No biometrics');
}
medium
A. No biometrics
B. false
C. true
D. Exception error

Solution

  1. Step 1: Check biometric availability

    The code checks if biometrics are available with canCheckBiometrics. If true, it proceeds.
  2. Step 2: Authenticate and print result

    If authentication succeeds, didAuthenticate is true and printed.
  3. Final Answer:

    true -> Option C
  4. Quick Check:

    Available and success = true [OK]
Hint: Success prints true, failure prints false or message [OK]
Common Mistakes:
  • Assuming it prints 'No biometrics' when available
  • Expecting false on success
  • Ignoring await causing errors
4. Identify the error in this Flutter biometric authentication snippet:
final didAuthenticate = await auth.authenticate(
  localizedReason: 'Scan fingerprint',
  useErrorDialogs: true,
  stickyAuth: true
);
if (didAuthenticate) {
  print('Access granted');
}
medium
A. No check if biometrics are available before authenticate
B. Incorrect parameter name localizedReason
C. Missing await keyword before authenticate
D. Missing else block after if

Solution

  1. Step 1: Review biometric availability check

    The code calls authenticate without checking canCheckBiometrics first, which may cause errors on devices without biometrics.
  2. Step 2: Validate other parts

    Await is present, parameter names are correct, and else block is optional.
  3. Final Answer:

    No check if biometrics are available before authenticate -> Option A
  4. Quick Check:

    Always check availability before authenticate [OK]
Hint: Check biometrics availability before authenticating [OK]
Common Mistakes:
  • Skipping availability check
  • Confusing parameter names
  • Thinking else block is mandatory
5. You want to secure a Flutter app so it only allows access if biometric authentication succeeds. Which sequence of steps correctly implements this using local_auth? A) Call authenticate directly without checking availability. B) Check canCheckBiometrics, then call authenticate, then proceed if true. C) Skip biometric checks and use a password instead. D) Call authenticate and ignore its result.
hard
A. Call authenticate directly without checking availability
B. Check canCheckBiometrics, then authenticate, then proceed if true
C. Skip biometrics and use password only
D. Call authenticate and ignore its result

Solution

  1. Step 1: Verify biometric availability

    Use canCheckBiometrics to ensure device supports biometrics before authenticating.
  2. Step 2: Authenticate and check result

    Call authenticate and proceed only if it returns true, ensuring secure access.
  3. Step 3: Avoid skipping checks or ignoring results

    Skipping availability or ignoring authentication result risks security.
  4. Final Answer:

    Check canCheckBiometrics, then authenticate, then proceed if true -> Option B
  5. Quick Check:

    Availability check + authenticate success = secure access [OK]
Hint: Always check availability before authenticating [OK]
Common Mistakes:
  • Calling authenticate without availability check
  • Ignoring authentication result
  • Using password instead of biometrics when asked
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard