Flutter本地认证插件local_auth_darwin的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter本地认证插件local_auth_darwin的使用

local_auth_darwin是Flutter中用于iOS和macOS平台实现本地认证功能的插件。它支持通过生物识别(如指纹、面部识别)或设备密码进行身份验证。

使用说明

该插件是被认可的,这意味着你可以直接使用local_auth包,而不需要在pubspec.yaml文件中显式添加local_auth_darwin依赖项。但是,如果你需要直接调用该插件提供的API,则需要将其添加到pubspec.yaml中。

示例Demo

下面是一个完整的示例代码,展示了如何在Flutter应用中使用local_auth_darwin进行本地认证:

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs, avoid_print

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart'; // 导入local_auth包
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  _SupportState _supportState = _SupportState.unknown;
  bool? _canCheckBiometrics;
  List<BiometricType>? _enrolledBiometrics;
  String _authorized = 'Not Authorized';
  bool _isAuthenticating = false;

  final LocalAuthentication _auth = LocalAuthentication();

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

  Future<void> _checkDeviceSupport() async {
    bool isSupported = await _auth.isDeviceSupported();
    setState(() {
      _supportState = isSupported ? _SupportState.supported : _SupportState.unsupported;
    });
  }

  Future<void> _checkBiometrics() async {
    try {
      bool deviceSupportsBiometrics = await _auth.canCheckBiometrics;
      setState(() {
        _canCheckBiometrics = deviceSupportsBiometrics;
      });
    } on PlatformException catch (e) {
      print(e);
    }
  }

  Future<void> _getEnrolledBiometrics() async {
    try {
      List<BiometricType> enrolledBiometrics = await _auth.getAvailableBiometrics();
      setState(() {
        _enrolledBiometrics = enrolledBiometrics;
      });
    } on PlatformException catch (e) {
      print(e);
    }
  }

  Future<void> _authenticate() async {
    try {
      setState(() {
        _isAuthenticating = true;
        _authorized = 'Authenticating';
      });
      bool authenticated = await _auth.authenticate(
        localizedReason: 'Let OS determine authentication method',
        options: const AuthenticationOptions(stickyAuth: true),
      );
      setState(() {
        _isAuthenticating = false;
        _authorized = authenticated ? 'Authorized' : 'Not Authorized';
      });
    } on PlatformException catch (e) {
      print(e);
      setState(() {
        _isAuthenticating = false;
        _authorized = 'Error - ${e.message}';
      });
    }
  }

  Future<void> _authenticateWithBiometrics() async {
    try {
      setState(() {
        _isAuthenticating = true;
        _authorized = 'Authenticating';
      });
      bool authenticated = await _auth.authenticate(
        localizedReason: 'Scan your fingerprint (or face or whatever) to authenticate',
        options: const AuthenticationOptions(stickyAuth: true, biometricOnly: true),
      );
      setState(() {
        _isAuthenticating = false;
        _authorized = authenticated ? 'Authorized' : 'Not Authorized';
      });
    } on PlatformException catch (e) {
      print(e);
      setState(() {
        _isAuthenticating = false;
        _authorized = 'Error - ${e.message}';
      });
    }
  }

  Future<void> _cancelAuthentication() async {
    await _auth.stopAuthentication();
    setState(() => _isAuthenticating = false);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: ListView(
          padding: const EdgeInsets.only(top: 30),
          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                if (_supportState == _SupportState.unknown)
                  const CircularProgressIndicator()
                else if (_supportState == _SupportState.supported)
                  const Text('This device is supported')
                else
                  const Text('This device is not supported'),
                const Divider(height: 100),
                Text('Device supports biometrics: $_canCheckBiometrics\n'),
                ElevatedButton(
                  onPressed: _checkBiometrics,
                  child: const Text('Check biometrics'),
                ),
                const Divider(height: 100),
                Text('Enrolled biometrics: $_enrolledBiometrics\n'),
                ElevatedButton(
                  onPressed: _getEnrolledBiometrics,
                  child: const Text('Get enrolled biometrics'),
                ),
                const Divider(height: 100),
                Text('Current State: $_authorized\n'),
                if (_isAuthenticating)
                  ElevatedButton(
                    onPressed: _cancelAuthentication,
                    child: const Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Text('Cancel Authentication'),
                        Icon(Icons.cancel),
                      ],
                    ),
                  )
                else
                  Column(
                    children: <Widget>[
                      ElevatedButton(
                        onPressed: _authenticate,
                        child: const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text('Authenticate'),
                            Icon(Icons.perm_device_information),
                          ],
                        ),
                      ),
                      ElevatedButton(
                        onPressed: _authenticateWithBiometrics,
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text(_isAuthenticating ? 'Cancel' : 'Authenticate: biometrics only'),
                            const Icon(Icons.fingerprint),
                          ],
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

enum _SupportState {
  unknown,
  supported,
  unsupported,
}

关键点解释

  • 导入依赖:确保在pubspec.yaml中添加了local_auth依赖。

    dependencies:
      flutter:
        sdk: flutter
      local_auth: ^2.0.0 # 确保版本号正确
    
  • 检查设备支持:通过_auth.isDeviceSupported()方法检查当前设备是否支持本地认证。

  • 生物识别支持:通过_auth.canCheckBiometrics属性判断设备是否支持生物识别,并通过_auth.getAvailableBiometrics()获取已注册的生物识别类型。

  • 身份验证:通过_auth.authenticate()方法进行身份验证,可以选择使用所有可用的身份验证方式(包括密码),或者仅使用生物识别方式进行验证。

以上代码提供了一个完整的示例,展示了如何在Flutter应用中集成并使用local_auth插件进行本地认证。


更多关于Flutter本地认证插件local_auth_darwin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地认证插件local_auth_darwin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter应用中使用local_auth_darwin插件进行本地认证的代码示例。local_auth_darwinlocal_auth包的一部分,专门用于在macOS和iOS平台上进行本地身份验证(如指纹或Face ID)。

首先,确保在pubspec.yaml文件中添加local_auth依赖:

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^1.0.0  # 请检查最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Dart代码中,你可以使用以下示例来展示如何使用local_auth进行本地认证:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Local Authentication Demo',
      home: LocalAuthDemo(),
    );
  }
}

class LocalAuthDemo extends StatefulWidget {
  @override
  _LocalAuthDemoState createState() => _LocalAuthDemoState();
}

class _LocalAuthDemoState extends State<LocalAuthDemo> {
  final LocalAuthentication _localAuthentication = LocalAuthentication();
  bool _authenticated = false;

  Future<void> _checkBiometrics() async {
    bool canCheckBiometrics;
    try {
      canCheckBiometrics = await _localAuthentication.canCheckBiometrics;
    } on PlatformException catch (e) {
      print("Failed to check biometrics: '${e.message}'.");
      canCheckBiometrics = false;
    }

    if (!canCheckBiometrics) {
      setState(() {
        _authenticated = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Device does not support biometrics.')),
      );
      return;
    }

    bool authenticated = false;
    try {
      authenticated = await _localAuthentication.authenticateWithBiometrics(
        localizedReason: 'Please authenticate to continue.',
        stickyAuth: true,
      );
    } on PlatformException catch (e) {
      print("Failed to authenticate: '${e.message}'.");
    }

    if (!authenticated) {
      setState(() {
        _authenticated = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Authentication failed.')),
      );
    } else {
      setState(() {
        _authenticated = true;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Authenticated successfully!')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Local Authentication Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _authenticated ? 'Authenticated' : 'Not Authenticated',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _checkBiometrics,
              child: Text('Authenticate'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 依赖添加:在pubspec.yaml文件中添加local_auth依赖。
  2. 导入包:在Dart文件中导入local_auth包。
  3. 检查设备是否支持生物识别:使用_localAuthentication.canCheckBiometrics来检查设备是否支持生物识别。
  4. 生物识别认证:调用_localAuthentication.authenticateWithBiometrics方法来触发认证流程。localizedReason参数是显示在认证界面上的提示信息,stickyAuth参数表示是否保持认证状态(在iOS上有效)。
  5. 处理认证结果:根据认证结果更新UI并显示相应的SnackBar消息。

注意事项

  • 确保在真实设备上进行测试,因为模拟器通常不支持生物识别功能。
  • 处理可能的异常,例如设备不支持生物识别或用户取消认证。
  • 在生产环境中,考虑添加更多的安全措施和用户体验优化。

希望这个示例能帮助你理解如何在Flutter应用中使用local_auth_darwin进行本地认证。

回到顶部