Flutter指纹识别插件secugen_plugin的使用

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

Flutter指纹识别插件secugen_plugin的使用

secugen_plugin 是一个用于连接 Secugen 设备并访问所有设备功能的新 Flutter 插件。

开始使用

本项目是一个 Flutter 插件包的起点,它包含 Android 和/或 iOS 平台特定的实现代码。

对于 Flutter 开发的帮助,请参阅 官方文档,该文档提供了教程、示例、移动开发指南和完整的 API 参考。

使用示例

以下是一个完整的示例代码,展示了如何使用 secugen_plugin 插件进行指纹识别。

import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:secugen_plugin/secugen_plugin.dart';

void main() {
  runApp(MaterialApp(home: const FirstScreen()));
}

class FirstScreen extends StatelessWidget {
  const FirstScreen({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo"),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const MyApp()),
              );
            },
            child: Text(
              "Biometric Demo",
            ),
          )
        ],
      ),
    );
  }
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _secugenPlugin = SecugenPlugin();

  int _timeout_ms = 3000, _quality = 80;

  String? _fingerprintMatchString;
  bool? _isDeviceReady, _isLedOn, _smartCaptureEnabled, _isFingerprintMatched;
  Uint8List? _fpImageBytes, _fpRegisterBytes, _fpVerifyBytes;
  ImageCaptureResult? _firstCaptureResult, _secondCaptureResult;

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

    _isDeviceReady = false;
    _setControls();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeDevice();
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 15,
              vertical: 20,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  '欢迎使用 Secugen 插件指纹 SDK 测试!!!',
                  style: TextStyle(
                    height: 1.35,
                    fontSize: 17,
                    fontWeight: FontWeight.w400,
                    color: Colors.black,
                  ),
                ),
                SizedBox(
                  height: 35,
                ),
                Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      flex: 1,
                      child: _actionButton(
                        btnText: '打开设备',
                        onPressed: _initializeDevice,
                      ),
                    ),
                    SizedBox(
                      width: MediaQuery.of(context).size.width * .07,
                    ),
                    Expanded(
                      flex: 1,
                      child: _deviceStatus(),
                    ),
                  ],
                ),
                SizedBox(
                  height: 25,
                ),
                IntrinsicHeight(
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: _fingerprintImage(imageBytes: _fpImageBytes),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * .07,
                      ),
                      Expanded(
                        flex: 1,
                        child: Column(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            _actionButton(
                              btnText: '自动开启捕获',
                              onPressed: () =>
                                  _isDeviceReady!
                                      ? _captureFingerprint(true)
                                      : null,
                            ),
                            _actionButton(
                              btnText: '手动关闭捕获',
                              onPressed: () =>
                                  _isDeviceReady!
                                      ? _captureFingerprint(false)
                                      : null,
                            ),
                            _switchButton(
                              switchVal: _isLedOn!,
                              switchText: 'LED',
                              onSwitch: _isDeviceReady!
                                  ? (val) {
                                      setState(() => _isLedOn = val);
                                      _toggleLed();
                                    }
                                  : null,
                            ),
                            _switchButton(
                              switchVal: _smartCaptureEnabled!,
                              switchText: '智能捕获',
                              onSwitch: _isDeviceReady!
                                  ? (val) {
                                      setState(
                                          () => _smartCaptureEnabled = val);
                                      _toggleSmartCapture();
                                    }
                                  : null,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 30,
                ),
                _fingerprintMatchStatus(),
                SizedBox(
                  height: 10,
                ),
                IntrinsicHeight(
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            _fingerprintImage(imageBytes: _fpRegisterBytes),
                            SizedBox(
                              height: 10,
                            ),
                            _actionButton(
                              btnText: '注册指纹',
                              onPressed: () =>
                                  _isDeviceReady!
                                      ? _captureFirstFinger()
                                      : null,
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * .07,
                      ),
                      Expanded(
                        flex: 1,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            _fingerprintImage(imageBytes: _fpVerifyBytes),
                            SizedBox(
                              height: 10,
                            ),
                            _actionButton(
                              btnText: '验证指纹',
                              onPressed: () =>
                                  _isDeviceReady!
                                      ? _captureSecondFinger()
                                      : null,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                ElevatedButton(
                  style: ButtonStyle(
                    elevation: MaterialStateProperty.all(1),
                    backgroundColor:
                        MaterialStateProperty.all(Colors.grey[300]),
                  ),
                  onPressed: _clearAllFiles,
                  child: Text(
                    "清除所有文件",
                    style: TextStyle(
                      letterSpacing: .65,
                      fontSize: 10,
                      fontWeight: FontWeight.w400,
                      color: Colors.black,
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _deviceStatus() {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 8,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            '状态:',
            style: TextStyle(
              fontSize: 12,
              color: Colors.black,
            ),
          ),
          Text(
            _isDeviceReady! ? '准备就绪' : '未准备好',
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w500,
              color: _isDeviceReady! ? Colors.green : Colors.red,
            ),
          ),
        ],
      ),
    );
  }

  Widget _fingerprintImage({required Uint8List? imageBytes}) {
    return Container(
      width: double.infinity,
      height: MediaQuery.of(context).size.height * .25,
      color: Colors.grey[200],
      child: imageBytes == null
          ? SizedBox()
          : Image.memory(imageBytes, fit: BoxFit.contain),
    );
  }

  Widget _actionButton({
    required String btnText,
    required Function()? onPressed,
  }) {
    return ElevatedButton(
      style: ButtonStyle(
        elevation: MaterialStateProperty.all(1),
        backgroundColor: MaterialStateProperty.all(Colors.grey[300]),
      ),
      onPressed: onPressed,
      child: Text(
        btnText,
        style: TextStyle(
          letterSpacing: .65,
          fontSize: 10,
          fontWeight: FontWeight.w400,
          color: Colors.black,
        ),
      ),
    );
  }

  Widget _switchButton(
      {required bool switchVal,
      required String switchText,
      required Function(bool)? onSwitch}) {
    return SwitchListTile(
      value: switchVal,
      onChanged: onSwitch,
      dense: true,
      visualDensity: VisualDensity(horizontal: -4, vertical: -4),
      contentPadding: EdgeInsets.fromLTRB(5, 0, 0, 0),
      title: Text(
        switchText,
        style: TextStyle(
          fontSize: 14,
          color: Colors.black,
        ),
      ),
    );
  }

  Widget _fingerprintMatchStatus() {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 8,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            '匹配状态:',
            style: TextStyle(
              fontSize: 12,
              color: Colors.black,
            ),
          ),
          Text(
            _fingerprintMatchString!,
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w500,
              color: _isFingerprintMatched == null
                  ? Colors.grey
                  : (_isFingerprintMatched! ? Colors.green : Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  void _setControls() {
    _fingerprintMatchString = '无状态可用';
    _isFingerprintMatched =
        _fpImageBytes = _fpRegisterBytes = _fpVerifyBytes = null;

    if (_isDeviceReady!) {
      _isLedOn = false;
      _smartCaptureEnabled = true;
    } else {
      _isLedOn = _smartCaptureEnabled = false;
    }

    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _initializeDevice() async {
    try {
      _isDeviceReady = await _secugenPlugin.initializeDevice();
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }

    _setControls();
  }

  Future<void> _toggleLed() async {
    _secugenPlugin.enableLed(_isLedOn!);
  }

  Future<void> _toggleSmartCapture() async {
    _secugenPlugin.enableSmartCapture(_isLedOn!);
  }

  Future<bool?> _clearAllFiles() async {
    final result = await _secugenPlugin.clearAllFiles();
    return result;
  }

  Future<void> _captureFingerprint(bool isAutoOn) async {
    _fpImageBytes = null;

    try {
      final captureResult =
          await _secugenPlugin.captureFingerprint(auto: isAutoOn);
      _fpImageBytes = captureResult!.imageBytes;
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }

    setState(() {});
  }

  Future<void> _captureFirstFinger() async {
    _fpRegisterBytes = _firstCaptureResult = _isFingerprintMatched = null;
    _fingerprintMatchString = '无状态可用';

    try {
      final captureResult = await _secugenPlugin.captureFingerprintWithQuality(
          timeout: _timeout_ms, quality: _quality);
      _fpRegisterBytes = captureResult!.imageBytes;
      _firstCaptureResult = captureResult;
      debugPrint(
          "_firstCaptureResult : ${_firstCaptureResult.toString()} \n _firstCaptureResult.imageFilePath ${_firstCaptureResult?.imageFilePath}");
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }

    setState(() {});
  }

  Future<void> _captureSecondFinger() async {
    _fpVerifyBytes = _secondCaptureResult = _isFingerprintMatched = null;
    _fingerprintMatchString = '无状态可用';

    try {
      final captureResult = await _secugenPlugin.captureFingerprintWithQuality(
          timeout: _timeout_ms, quality: _quality);
      _fpVerifyBytes = captureResult!.imageBytes;
      _secondCaptureResult = captureResult;
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }

    setState(() {});

    if (_firstCaptureResult != null && _secondCaptureResult != null) {
      _verifyFingerprints();
    }
  }

  Future<void> _verifyFingerprints() async {
    try {
      final result = await _secugenPlugin.verifyFingerprint(
          firstBytes: _firstCaptureResult!.rawBytes!,
          secondBytes: _secondCaptureResult!.rawBytes!);
      _isFingerprintMatched = result;
      _fingerprintMatchString =
          _isFingerprintMatched! ? '匹配成功' : '匹配失败';
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }

    setState(() {});
  }

  Future<void> _getScore() async {
    try {
      final result = await _secugenPlugin.getMatchingScore(
          firstBytes: _firstCaptureResult!.rawBytes!,
          secondBytes: _secondCaptureResult!.rawBytes!);
    } on SgfplibException catch (e) {
      print(e.message);
      _showAlertDialog(context, e.message!);
    }
  }

  void _showAlertDialog(BuildContext context, String message) {
    AlertDialog alert = AlertDialog(
      title: Text("SecuGen 指纹 SDK"),
      content: Text(message),
      actions: [
        TextButton(
          child: Text("确定"),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ],
    );

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}

更多关于Flutter指纹识别插件secugen_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter指纹识别插件secugen_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中集成和使用secugen_plugin指纹识别插件的示例代码。这个插件假设是用于与SecuGen的指纹识别设备进行交互。请注意,实际使用时,你需要确保已经安装了secugen_plugin,并且你的设备支持该插件。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  secugen_plugin: ^x.y.z  # 替换为实际的版本号

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

2. 初始化插件

在你的Flutter应用的主要入口文件(通常是main.dart)中,初始化secugen_plugin

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FingerprintScreen(),
    );
  }
}

class FingerprintScreen extends StatefulWidget {
  @override
  _FingerprintScreenState createState() => _FingerprintScreenState();
}

class _FingerprintScreenState extends State<FingerprintScreen> {
  late SecuGenPlugin secuGenPlugin;

  @override
  void initState() {
    super.initState();
    // 初始化插件
    secuGenPlugin = SecuGenPlugin();
    // 可以在这里进行其他初始化操作,比如请求权限等
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fingerprint Scanner'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Scan your fingerprint'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                try {
                  // 假设scanFingerprint是一个用于扫描指纹的方法
                  String result = await secuGenPlugin.scanFingerprint();
                  // 处理扫描结果
                  print('Fingerprint scan result: $result');
                } catch (e) {
                  // 处理错误
                  print('Error scanning fingerprint: $e');
                }
              },
              child: Text('Scan Fingerprint'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 插件方法实现

注意:由于secugen_plugin是一个假设的插件名称,并且Flutter社区可能没有现成的这个插件,你需要参考实际的插件文档来实现具体的方法。以下是一个假设的scanFingerprint方法实现,你可能需要根据实际的插件API进行调整。

class SecuGenPlugin {
  // 假设这是插件的一个静态方法,用于扫描指纹
  Future<String> scanFingerprint() async {
    // 调用原生平台代码进行指纹扫描
    // 这里应该有一个实际的平台通道实现
    // 假设返回的是一个指纹模板字符串
    return "dummy_fingerprint_template";
  }
}

注意事项

  1. 权限:确保你的应用已经请求并获得了必要的权限,比如访问设备硬件的权限。
  2. 平台通道:实际的插件实现会涉及到Flutter与原生平台(Android和iOS)之间的通信,你需要根据插件的文档来实现平台通道(MethodChannel)的部分。
  3. 错误处理:在实际应用中,你应该添加更多的错误处理逻辑,比如处理设备不支持指纹识别的情况,或者用户取消扫描操作等。

由于secugen_plugin可能是一个假设的插件名称,如果它不存在,你可能需要寻找一个现有的Flutter指纹识别插件,或者自己编写原生代码并通过平台通道与Flutter进行交互。

回到顶部