Flutter面部认证插件face_authenticator的使用

FaceAuthenticator - Flutter 插件

FaceAuthenticator 使用指南

FaceAuthenticator 是一个用于调用 Android 和 iOS 原生 SDK 的 Flutter 插件。如果您有任何疑问,请发送邮件至我们的移动开发负责人邮箱:daniel.seitenfus@combateafraude.com。

隐私政策与使用条款

在使用本插件时,请确保您已同意我们的隐私政策使用条款


系统要求

以下是使用 FaceAuthenticator 所需的最低配置:

配置项 版本要求
Flutter 1.12+
Dart 2.12+
Android API 21+
iOS 11.0+

如果您的 Dart 版本低于 2.12,请检查兼容版本


配置步骤

Android 配置

在文件 ROOT_PROJECT/android/app/build.gradle 中添加以下内容:

android {
    ...
    dataBinding.enabled = true
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}

iOS 配置

在文件 ROOT_PROJECT/ios/Podfile 中添加以下内容:

source 'https://github.com/combateafraude/iOS.git'
source 'https://cdn.cocoapods.org/' # 或者 'https://github.com/CocoaPods/Specs' 如果 CDN 不可用

最后,在文件 ROOT_PROJECT/ios/Runner/Info.plist 中添加相机权限:

<key>NSCameraUsageDescription</key>
<string>为了拍摄自拍</string>

Flutter 配置

ROOT_PROJECT/pubspec.yaml 文件中添加插件依赖:

dependencies:  
  face_authenticator:
    git:
      url: https://github.com/combateafraude/Flutter.git
      ref: face-authenticator-v3.9.0

使用示例

以下是一个完整的使用示例,展示如何通过 FaceAuthenticator 进行面部认证。

import 'package:face_authenticator/face_authenticator.dart';
import 'package:face_authenticator/result/face_authenticator_failure.dart';
import 'package:face_authenticator/result/face_authenticator_result.dart';
import 'package:face_authenticator/result/face_authenticator_success.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _result = ""; // 结果存储
  String _description = ""; // 描述信息存储

  String mobileToken = ""; // 移动端令牌
  String peopleId = ""; // 用户唯一标识(如身份证号)

  [@override](/user/override)
  void initState() {
    super.initState();

    // 请求权限
    requestPermissions();
  }

  void requestPermissions() async {
    await [
      Permission.camera,
    ].request();
  }

  void startFaceAuthenticator() async {
    String result = "";
    String description = "";

    // 初始化 FaceAuthenticator
    FaceAuthenticator faceAuthenticator =
        new FaceAuthenticator(mobileToken: mobileToken);
    faceAuthenticator.setPeopleId(peopleId);

    try {
      // 启动面部认证
      FaceAuthenticatorResult faceAuthenticatorResult =
          await faceAuthenticator.start();

      // 处理结果
      if (faceAuthenticatorResult is FaceAuthenticatorSuccess) {
        result = "Success!";
        description += "\n\tauthenticated: " +
            (faceAuthenticatorResult.authenticated ? "true" : "false") +
            "\n\tsignedResponse: " +
            (faceAuthenticatorResult.signedResponse != null
                ? faceAuthenticatorResult.signedResponse
                : "null");
      } else if (faceAuthenticatorResult is FaceAuthenticatorFailure) {
        result = "Falha!";
        description = "\tType: " +
            faceAuthenticatorResult.type +
            "\n\tMessage: " +
            faceAuthenticatorResult.message;
      } else {
        result = "Closed!";
      }
    } on PlatformException catch (err) {
      result = "Exception!";
      description = err.message;
    }

    // 更新 UI
    if (!mounted) return;

    setState(() {
      _result = result;
      _description = description;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('FaceAuthenticator 插件示例'),
        ),
        body: Container(
          margin: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              // 开始面部认证按钮
              Row(
                children: [
                  ElevatedButton(
                    child: Text('开始面部认证'),
                    onPressed: () async {
                      startFaceAuthenticator();
                    },
                  )
                ],
              ),
              // 显示结果
              Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 10.0),
                    child: Text("结果: $_result"),
                  )
                ],
              ),
              // 显示描述信息
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      "描述:\n$_description",
                      overflow: TextOverflow.clip,
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
1 回复

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


face_authenticator 是一个用于在 Flutter 应用中实现面部认证的插件。它可以帮助开发者轻松地将面部识别功能集成到应用中,用于用户身份验证或安全访问控制。以下是如何在 Flutter 项目中使用 face_authenticator 插件的步骤。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 face_authenticator 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  face_authenticator: ^1.0.0  # 请使用最新版本

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

2. 配置权限

面部认证通常需要访问设备的摄像头和存储权限。在 AndroidManifest.xmlInfo.plist 中添加必要的权限。

AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Info.plist:

<key>NSCameraUsageDescription</key>
<string>We need access to your camera for facial authentication.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library for facial authentication.</string>

3. 初始化插件

在 Flutter 应用中初始化 face_authenticator 插件。

import 'package:face_authenticator/face_authenticator.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FaceAuthenticator.initialize();
  runApp(MyApp());
}

4. 使用面部认证功能

在应用中调用 face_authenticator 提供的 API 来进行面部认证。

注册面部数据

Future<void> registerFace() async {
  try {
    bool success = await FaceAuthenticator.registerFace();
    if (success) {
      print("Face registration successful!");
    } else {
      print("Face registration failed.");
    }
  } catch (e) {
    print("Error during face registration: $e");
  }
}

验证面部数据

Future<void> authenticateFace() async {
  try {
    bool success = await FaceAuthenticator.authenticateFace();
    if (success) {
      print("Face authentication successful!");
    } else {
      print("Face authentication failed.");
    }
  } catch (e) {
    print("Error during face authentication: $e");
  }
}

5. 处理结果

根据面部认证的结果,更新 UI 或执行其他操作。

ElevatedButton(
  onPressed: () async {
    await authenticateFace();
    // 根据认证结果更新 UI
  },
  child: Text("Authenticate Face"),
);

6. 处理错误

在使用过程中,可能会遇到各种错误,如权限被拒绝、设备不支持面部识别等。确保在代码中处理这些错误,并向用户提供友好的提示。

try {
  bool success = await FaceAuthenticator.authenticateFace();
  if (success) {
    // 认证成功
  } else {
    // 认证失败
  }
} on PlatformException catch (e) {
  print("PlatformException: ${e.message}");
} catch (e) {
  print("Unexpected error: $e");
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!