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

Flutter实现APP要求用户设置设备本地认证方式的方法

解决方案:Flutter检测设备本地认证状态并引导设置

1. 依赖库选择

使用local_auth库检测本地认证状态,搭配url_launcher库跳转系统设置。

2. 安装依赖

在pubspec.yaml中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^2.1.6
  url_launcher: ^6.1.12

执行flutter pub get完成依赖安装。

3. 检测设备是否启用本地认证

核心逻辑:先验证设备是否支持本地认证,再通过尝试发起认证请求、捕获特定错误,判断用户是否未设置任何认证方式(PIN/密码/生物识别)。

代码示例:

import 'package:flutter/foundation.dart';
import 'package:local_auth/local_auth.dart';
import 'package:url_launcher/url_launcher.dart';

final LocalAuthentication _localAuth = LocalAuthentication();

Future<bool> hasLocalAuthEnabled() async {
  bool isDeviceSupported = await _localAuth.isDeviceSupported();
  if (!isDeviceSupported) return false;

  try {
    // 发起认证请求(无需完成认证,仅用于判断是否存在可用认证方式)
    await _localAuth.authenticate(
      localizedReason: '检查设备认证状态',
      options: const AuthenticationOptions(
        biometricOnly: false, // 允许PIN/密码等非生物识别方式
        useErrorDialogs: false, // 禁用系统默认错误弹窗
        stickyAuth: true,
      ),
    );
    return true;
  } catch (e) {
    if (e is PlatformException) {
      // iOS:not_enrolled 表示未设置生物识别(iOS需先设密码才能开生物识别,因此连密码也未设置)
      // Android:no_device_credential 表示未设置任何PIN/密码/图案
      if (e.code == 'not_enrolled' || e.code == 'no_device_credential') {
        return false;
      }
    }
    return false;
  }
}

4. 引导用户进入系统设置

检测到未启用本地认证时,弹出提示对话框,点击确认后跳转至系统设置页面:

void showAuthSetupPrompt(BuildContext context) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: const Text('安全提示'),
      content: const Text('为保障账号安全,请先设置设备PIN码/密码或生物识别认证。'),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () async {
            Navigator.pop(context);
            // 跳转对应系统设置页面
            if (defaultTargetPlatform == TargetPlatform.iOS) {
              await launchUrl(Uri.parse('app-settings:'));
            } else if (defaultTargetPlatform == TargetPlatform.android) {
              await launchUrl(Uri.parse('https://settings.SECURITY_SETTINGS'));
            }
          },
          child: const Text('去设置'),
        ),
      ],
    ),
  );
}

5. 完整启动检测流程

在APP初始化页面的initState中调用检测逻辑:

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

Future<void> _checkAuthStatus() async {
  bool hasAuth = await hasLocalAuthEnabled();
  if (!hasAuth) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      showAuthSetupPrompt(context);
    });
  }
}

注意事项

  • iOS需在Info.plist中添加生物识别权限描述:
    <key>NSFaceIDUsageDescription</key>
    <string>用于验证设备认证状态,保障账号安全</string>
    
  • Android需在AndroidManifest.xml中添加权限:
    <uses-permission android:name="android.permission.USE_BIOMETRIC" />
    <uses-permission android:name="android.permission.USE_FINGERPRINT" />
    
  • Android部分机型跳转设置页面的URI可能存在差异,可根据实际机型调整跳转路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:06:13