Flutter生物识别认证插件simple_biometric的使用

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

Flutter生物识别认证插件simple_biometric的使用

Simple Biometric 是一个用于在Flutter应用中实现生物识别认证的插件。它提供了简单易用的API,支持Android和iOS平台,并允许定制认证对话框。

特性

  • 简单易用的生物识别认证API。
  • 支持Android和iOS平台。
  • 可定制的认证对话框,包括标题、描述和取消按钮文本。

初步配置

对于Android:

  1. 在主Android文件中添加以下导入和类:
    import io.flutter.embedding.android.FlutterFragmentActivity;
       
    class MainActivity: FlutterFragmentActivity() {
    }
    
  2. AndroidManifest.xml中添加权限:
    <uses-permission android:name="android.permission.USE_BIOMETRIC"/>
    

对于iOS:

  1. Info.plist文件中添加以下键值对:
    <key>NSFaceIDUsageDescription</key>
    <string>This app requires facial authentication to access certain functionalities.</string>
    <key>NSTouchIDUsageDescription</key>
    <string>This app requires fingerprint authentication to access certain functionalities.</string>
    

使用方法

导入包

import 'package:simple_biometric/simple_biometric.dart';

Android特定:检查生物识别硬件是否可用

在尝试认证之前,请先检查生物识别硬件是否可用:

final isBiometricAvailable = await _simpleBiometric.isAndroidBiometricHardwareAvailable();

iOS特定:检查生物识别类型

在iOS上,可以检查可用的生物识别类型(Face ID或Touch ID):

IOSBiometricType iosBiometricType = await SimpleBiometric.getIOSBiometricType();

if(iosBiometricType == IOSBiometricType.faceId) {
  // Face ID 可用
} else if (iosBiometricType == IOSBiometricType.touchId) {
  // Touch ID 可用
}

使用生物识别进行认证

通过调用showBiometricPrompt方法并提供可选的自定义参数来进行认证:

try{
  BiometricStatusResult? result = await SimpleBiometric.showBiometricPrompt(
    title: 'Biometric Authentication',
    description: 'Authenticate using your biometric credential',
    cancelText: 'Cancel',
  );

  switch (result) {
    case BiometricStatusResult.authSuccess:
      log('Authentication successful');
      break;
    // 其他情况处理...
    default:
      if (Platform.isIOS && _biometricType.isNotEmpty) {
        log('Authentication config unavailable');
        _showConfigBiometricDialog();
      }
      break;
  }
} catch (e) {
}

示例Demo

下面是一个完整的示例应用程序,演示了如何使用Simple Biometric插件:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:simple_biometric/simple_biometric.dart';
import 'package:simple_biometric/enums.dart';

void main() {
  runApp(const LoginApp());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Biometric Login',
      home: LoginPage(),
    );
  }
}

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

  [@override](/user/override)
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final SimpleBiometric _simpleBiometric = SimpleBiometric();
  bool _isBiometricAvailable = false;
  bool _biometricEnabled = false;
  String _biometricType = "";

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

  Future<void> _initBiometricType() async {
    if (Platform.isAndroid) {
      setState(() {
        _biometricType = "";
      });
    }
    if (Platform.isIOS) {
      final value = await _simpleBiometric.getIOSBiometricType();
      setState(() {
        _biometricType = value == IOSBiometricType.faceId ? "Face Id" : value == IOSBiometricType.touchId ? "Touch ID" : "";
      });
    }
    await _checkBiometricAvailability();
  }

  Future<void> _checkBiometricAvailability() async {
    if (Platform.isAndroid) {
      final isBiometricAvailable = await _simpleBiometric.isAndroidBiometricHardwareAvailable();
      setState(() {
        _isBiometricAvailable = isBiometricAvailable;
      });
    }
    if (Platform.isIOS) {
      setState(() {
        _isBiometricAvailable = _biometricType.isNotEmpty;
      });
    }
  }

  Future<void> _authenticate() async {
    if (_biometricEnabled) {
      try {
        final result = await _simpleBiometric.showBiometricPrompt(
          title: 'Biometric Authentication',
          description: 'Authenticate using your biometric credential',
          cancelText: 'Cancel',
        );
        _handleAuthenticationResult(result);
      } catch (e) {
        // error handling
      }
    }
  }

  void _handleAuthenticationResult(BiometricStatusResult? result) {
    switch (result) {
      case BiometricStatusResult.authSuccess:
        debugPrint('Authentication successful');
        break;
      // 其他情况处理...
      default:
        if (Platform.isIOS && _biometricType.isNotEmpty) {
          debugPrint('Authentication config unavailable');
          _showConfigBiometricDialog();
        }
        break;
    }
  }

  void _showConfigBiometricDialog() {
    if (context.mounted) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('No Biometrics Available'),
          content: const Text('Please go to settings and set up your biometric authentication.'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('OK'),
            ),
          ],
        ),
      );
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Biometric Login'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              controller: _usernameController,
              decoration: const InputDecoration(labelText: 'Username'),
            ),
            TextField(
              controller: _passwordController,
              decoration: const InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            if (_isBiometricAvailable)
              CheckboxListTile(
                title: Text('Enable ${_biometricType.isNotEmpty ? _biometricType : "biometric"} access'),
                value: _biometricEnabled,
                onChanged: (value) {
                  setState(() {
                    _biometricEnabled = value!;
                  });
                },
              ),
            ElevatedButton(
              onPressed: _authenticate,
              child: const Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用simple_biometric插件进行生物识别认证的代码案例。这个插件支持指纹、面部识别等多种生物识别方式。

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

dependencies:
  flutter:
    sdk: flutter
  simple_biometric: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来获取依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用simple_biometric插件:

  1. 导入插件
import 'package:simple_biometric/simple_biometric.dart';
  1. 配置和使用

以下是一个完整的示例,展示如何在Flutter应用中使用simple_biometric插件进行生物识别认证:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  SimpleBiometric _simpleBiometric = SimpleBiometric();
  bool _isAuthenticated = false;

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

  Future<void> authenticateUser() async {
    try {
      bool authenticated = await _simpleBiometric.authenticate(
        localizedReason: 'Please authenticate to continue',
        stickyAuth: true,
      );

      setState(() {
        _isAuthenticated = authenticated;
      });

      if (_isAuthenticated) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Success'),
              content: Text('User authenticated successfully!'),
              actions: <Widget>[
                FlatButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      } else {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Failed'),
              content: Text('Authentication failed or canceled by user.'),
              actions: <Widget>[
                FlatButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      print('Error during authentication: $e');
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Error'),
            content: Text('An error occurred during authentication.'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Biometric Authentication Demo'),
      ),
      body: Center(
        child: Text(
          _isAuthenticated ? 'Authenticated' : 'Not Authenticated',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

在这个示例中:

  • 我们创建了一个Flutter应用,其中包含一个主页面MyHomePage
  • MyHomePageinitState方法中,我们调用authenticateUser函数来启动生物识别认证流程。
  • authenticateUser函数使用_simpleBiometric.authenticate方法来触发认证。如果认证成功,会显示一个成功的对话框;如果认证失败或取消,会显示一个失败的对话框。
  • 页面中心显示当前的认证状态。

请注意,在实际应用中,你可能需要根据用户的具体操作(如点击按钮)来触发认证流程,而不是在initState中直接调用。此外,还需要处理各种可能的错误情况,例如生物识别硬件不可用、用户拒绝授权等。

回到顶部