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

如何在Flutter应用中使用local_auth包实现生物识别认证?

我正在开发一款Flutter应用,希望添加生物识别认证(如指纹或人脸识别)功能,以提升用户使用的安全性与便捷性。经调研后,我决定采用local_auth包来处理生物识别认证流程,但不确定如何将该包集成到应用中,也不清楚如何处理认证流程。恳请提供使用local_auth包在Flutter应用中实现生物识别认证的指导,以及可参考的代码示例或教程?以下是我已编写的用于处理邮箱和密码用户认证的相关代码:

import 'package:firebase_auth/firebase_auth.dart';

class AuthenticationService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  Future<UserCredential> signIn({String email, String password}) async {
    return await _firebaseAuth.signInWithEmailAndPassword(
        email: email, password: password);
  }

  Future<UserCredential> signUp({String email, String password}) async {
    return await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
  }

  Future<void> signOut() async {
    return await _firebaseAuth.signOut();
  }

  Stream<User> get currentUser {
    return _firebaseAuth.authStateChanges();
  }
}

基于local_auth实现生物识别认证方案

1. 添加依赖

在项目的pubspec.yaml中引入local_auth包(建议使用最新稳定版):

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^2.1.6
  firebase_auth: ^4.6.0 # 保持你现有版本即可

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

2. 配置平台权限

Android端

在android/app/src/main/AndroidManifest.xml中添加权限声明:

<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" /> <!-- 兼容Android 10及以下版本 -->

同时确保android/app/build.gradle的minSdkVersion不低于21:

android {
    defaultConfig {
        minSdkVersion 21
    }
}

iOS端

在ios/Runner/Info.plist中添加生物识别使用说明(iOS强制要求):

<key>NSFaceIDUsageDescription</key>
<string>验证生物识别以快速登录,保障账号安全</string>

3. 扩展现有认证服务类

在你已有的AuthenticationService中新增生物识别相关方法:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:local_auth/local_auth.dart';

class AuthenticationService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final LocalAuthentication _localAuth = LocalAuthentication();

  // 原有邮箱密码认证方法保留
  Future<UserCredential> signIn({String? email, String? password}) async {
    return await _firebaseAuth.signInWithEmailAndPassword(
        email: email!, password: password!);
  }

  Future<UserCredential> signUp({String? email, String? password}) async {
    return await _firebaseAuth.createUserWithEmailAndPassword(
        email: email!, password: password!);
  }

  Future<void> signOut() async {
    return await _firebaseAuth.signOut();
  }

  Stream<User?> get currentUser {
    return _firebaseAuth.authStateChanges();
  }

  // 新增生物识别方法
  /// 检查设备是否支持生物识别
  Future<bool> isBiometricAvailable() async {
    final canCheck = await _localAuth.canCheckBiometrics;
    final isSupported = await _localAuth.isDeviceSupported();
    return canCheck && isSupported;
  }

  /// 获取设备支持的生物识别类型(如指纹、人脸识别)
  Future<List<BiometricType>> getSupportedBiometrics() async {
    return await _localAuth.getAvailableBiometrics();
  }

  /// 发起生物识别认证
  Future<bool> authenticateWithBiometrics() async {
    try {
      return await _localAuth.authenticate(
        localizedReason: '请验证身份以登录',
        options: const AuthenticationOptions(
          biometricOnly: true, // 仅允许生物识别,不允许 fallback 到设备密码
          stickyAuth: true, // 应用切换到后台再返回时,保持认证状态
        ),
      );
    } catch (_) {
      return false;
    }
  }
}

4. 在UI中集成生物识别功能

示例登录页面,支持密码登录和生物识别快速登录:

import 'package:flutter/material.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _authService = AuthenticationService();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isBiometricAvailable = false;

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

  Future<void> _checkBiometricSupport() async {
    _isBiometricAvailable = await _authService.isBiometricAvailable();
    setState(() {});
  }

  Future<void> _handleBiometricLogin() async {
    final isAuthenticated = await _authService.authenticateWithBiometrics();
    if (isAuthenticated) {
      // 若用户已通过邮箱密码登录过,直接进入主页
      if (_authService.currentUser.value != null) {
        Navigator.pushReplacementNamed(context, '/home');
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请先使用邮箱密码完成首次登录')),
        );
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('生物识别验证失败,请重试')),
      );
    }
  }

  Future<void> _handlePasswordLogin() async {
    try {
      await _authService.signIn(
        email: _emailController.text,
        password: _passwordController.text,
      );
      Navigator.pushReplacementNamed(context, '/home');
    } on FirebaseAuthException catch (e) {
      String message = '登录失败';
      if (e.code == 'user-not-found') {
        message = '未找到该用户';
      } else if (e.code == 'wrong-password') {
        message = '密码错误';
      }
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('账号登录')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _emailController,
              decoration: const InputDecoration(labelText: '邮箱'),
              keyboardType: TextInputType.emailAddress,
            ),
            TextField(
              controller: _passwordController,
              decoration: const InputDecoration(labelText: '密码'),
              obscureText: true,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _handlePasswordLogin,
              child: const Text('密码登录'),
            ),
            if (_isBiometricAvailable)
              Padding(
                padding: const EdgeInsets.only(top: 12),
                child: ElevatedButton(
                  onPressed: _handleBiometricLogin,
                  child: const Text('生物识别登录'),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

关键注意事项

  • 首次登录必须使用邮箱密码,建立Firebase Auth会话后,才能使用生物识别快速登录。
  • authenticate方法的localizedReason需明确说明生物识别的用途,iOS系统会将该文本显示在认证弹窗中。
  • 需处理多种异常场景:设备不支持生物识别、用户主动取消认证、验证失败等,给用户明确的反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:42:48