You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用local_auth时如何实现指纹与图案解锁的选择切换

解决方案

1. 版本与基础配置调整

首先将local_auth升级到2.1.0及以上版本,该版本新增了单独调用设备凭据认证的能力,无需关闭系统生物识别即可唤起PIN、图案、密码验证。
安卓端需在android/app/src/main/AndroidManifest.xml中添加认证权限:

<!-- 适配安卓6.0及以上版本生物识别权限 -->
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<!-- 兼容安卓10以下旧设备指纹权限 -->
<uses-permission android:name="android.permission.USE_FINGERPRINT" android:maxSdkVersion="28" />

iOS端需在ios/Runner/Info.plist中添加面容ID使用说明:

<key>NSFaceIDUsageDescription</key>
<string>需要使用面容ID完成身份验证</string>

2. 实现用户自主选择认证方式逻辑

2.1 先检测设备支持的认证类型

调用local_auth提供的检测接口,提前判断设备可用的认证能力,用于动态生成应用内的选项列表:

import 'package:local_auth/local_auth.dart';

final LocalAuthentication auth = LocalAuthentication();

// 检测是否支持设备凭据认证(PIN/图案/密码)
bool supportDeviceCredentials = await auth.isDeviceSupported();
// 检测可用的生物识别类型(指纹/面容ID)
List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();
bool supportBiometrics = availableBiometrics.isNotEmpty;

2.2 不同选择对应的调用逻辑

你可以在应用设置页新增认证方式选择项,根据用户的选择调用对应参数的认证接口:

  • 用户选择「仅设备凭据(PIN/图案/密码)」时的调用代码:
bool authenticated = await auth.authenticate(
  localizedReason: '请验证身份以继续',
  options: const AuthenticationOptions(
    useErrorDialogs: true,
    stickyAuth: true,
    // 关闭生物识别,仅唤起设备凭据认证
    biometricOnly: false,
    deviceCredentialsOnly: true,
  ),
);
  • 用户选择「优先生物识别,失败可切换设备凭据」时的调用代码:
bool authenticated = await auth.authenticate(
  localizedReason: '请验证身份以继续',
  options: const AuthenticationOptions(
    useErrorDialogs: true,
    stickyAuth: true,
    // 允许生物识别和设备凭据两种方式,系统弹窗会自带「切换到密码/图案」入口
    biometricOnly: false,
  ),
);
  • 用户选择「仅生物识别」时的调用代码:
bool authenticated = await auth.authenticate(
  localizedReason: '请验证生物特征以继续',
  options: const AuthenticationOptions(
    useErrorDialogs: true,
    stickyAuth: true,
    // 仅允许生物识别认证
    biometricOnly: true,
  ),
);

3. 兼容低版本local_auth的替代方案

如果暂时无法升级依赖,可以调用认证接口时保持biometricOnly: false,系统生物识别弹窗底部会默认显示「使用其他验证方式」的选项,用户点击后即可切换到图案、PIN等设备凭据验证,无需关闭系统生物识别功能。

内容的提问来源于stack exchange,提问作者Tologon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:45:03