How to use face ID in Flutter

We’ll learn how to perform Local authentication with a flutter app.

Basically, we’ll be using the Face ID authentication method

Lets get to it.

Import the local_auth package from pub

Create a new dart file an paste this code:

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

class FaceID extends StatefulWidget {
  @override
  _FaceIDState createState() => _FaceIDState();
}

class _FaceIDState extends State<FaceID> {
  final LocalAuthentication localAuth = LocalAuthentication();
  bool _canCheckBiometric = false;
  String _authorizeText = 'Not Authorized!';

  List<BiometricType> availableBiometrics = List<BiometricType>();

  Future<void> _authorize() async {
    bool _isAuthorized = false;
    try {
      const iosStrings = const IOSAuthMessages(
          cancelButton: 'Cancel Auth',
          goToSettingsButton: 'Goto Settings',
          goToSettingsDescription: 'Please set up your Touch ID.',
          lockOut: 'Please re-enable your Touch ID');

      _isAuthorized = await localAuth.authenticateWithBiometrics(
          localizedReason: 'Please authenticate to Complete this process',
          useErrorDialogs: false,
          iOSAuthStrings: iosStrings);
    } on PlatformException catch (e) {
      print(e);
    }

    if (!mounted) return;

    setState(() {
      if (_isAuthorized) {
        _authorizeText = "Authorized Successfully!";
      } else {
        _authorizeText = "Not Authorized!";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Face ID Auth Example')),
      body: Center(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(_authorizeText),
          ),
          RaisedButton(
            child: Text('Authorize'),
            color: Colors.red,
            onPressed: _authorize,
          )
        ],
      )),
    );
  }
}

In main.dart:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new FaceID(),
    );
  }
}

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.