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

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

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

文档说明

Flutter插件,允许您生成密钥对并使用生物识别进行加密签名。

该插件受本地_auth插件的影响很大。有关详细信息,请参阅本地_auth插件文档:https://github.com/flutter/plugins/tree/master/packages/local_auth

使用示例

import 'package:flutter_biometrics/flutter_biometrics.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _publicKey = 'Not retrieved/Not set';
  String _signature = 'Unknown';
  String _payload = 'Zmx1dHRlcl9iaW9tZXRyaWNz';

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

  Future<void> createKeys() async {
    var biometrics = FlutterBiometrics();
    String publicKey = await biometrics.createKeys(
        reason: 'Please authenticate to generate keys');

    setState(() {
      _publicKey = publicKey;
    });

    if (!mounted) return;
  }

  Future<void> sign() async {
    var biometrics = FlutterBiometrics();
    String signature = await biometrics.sign(
        payload: _payload,
        reason: ' Please authenticate to sign specified payload');

    setState(() {
      _signature = signature;
    });

    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('flutter_biometrics'),
          backgroundColor: Colors.blueGrey,
        ),
        body: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(top: 20.0),
              alignment: Alignment.center,
              child: Text("1. Generate a key pair", style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),),
            ),
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 20.0),
              child: RaisedButton(
                onPressed: createKeys,
                child: Text("Create keys"),
              ),
            ),
            Container(
              alignment: Alignment.center,
              width: double.infinity,
              padding: EdgeInsets.all(10.0),
              child: Text(
                "Public key: $_publicKey",
                style: TextStyle(color: Colors.white),
              ),
              margin: EdgeInsets.only(top: 10.0),
              color: Colors.blueGrey,
            ),
            Container(
              margin: EdgeInsets.only(top: 20.0, bottom: 10.0),
              alignment: Alignment.center,
              child: Text("2. Provide a payload to sign", style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),),
            ),
            Container(
              margin: EdgeInsets.only(top: 20.0),
              alignment: Alignment.center,
              padding: EdgeInsets.all(10.0),
              child: TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Payload to sign (Base64 encoded)',
                  hintText: 'Zmx1dHRlcl9iaW9tZXRyaWNz',
                ),
                onChanged: (value) {
                  setState(() {
                    _payload = value;
                  });
                },
              ),
            ),
            Center(
              child: RaisedButton(
                onPressed: sign,
                child: Text("Sign '$_payload'"),
              ),
            ),
            Container(
              width: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.all(10.0),
              child: Text(
                "Signature: $_signature",
                style: TextStyle(color: Colors.white),
              ),
              margin: EdgeInsets.only(top: 10.0),
              color: Colors.blueGrey,
            ),
          ],
        ),
      ),
    );
  }
}

Android集成(参考自local_auth)

注意,local_auth插件需要使用FragmentActivity而不是Activity。可以通过在AndroidManifest.xml文件中将USE_FINGERPRINT权限添加到<code>FlutterFragmentActivity</code>来轻松实现这一点,而不是<code>FlutterActivity</code>

更新项目中的AndroidManifest.xml文件以包含<code>USE_FINGERPRINT</code>权限:

&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app"&gt;
  &lt;uses-permission android:name="android.permission.USE_FINGERPRINT"/&gt;
&lt;/manifest&gt;

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

1 回复

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


当然,下面是一个关于如何使用 flutter_biometrics 插件进行生物识别认证的 Flutter 代码示例。这个插件支持指纹、面部识别等多种生物识别方式,具体取决于设备的硬件支持情况。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_biometrics 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_biometrics: ^5.0.0  # 请根据需要调整版本号

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

以下是一个简单的 Flutter 应用示例,展示如何使用 flutter_biometrics 进行生物识别认证:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  bool _isAuthenticated = false;

  void _authenticate() async {
    try {
      bool canAuthenticate = await FlutterBiometrics.authenticate(
        context: context,
        authenticated: () async {
          setState(() {
            _isAuthenticated = true;
          });
          // 用户认证成功后的处理逻辑
          print("Authenticated successfully!");
        },
        failed: () {
          setState(() {
            _isAuthenticated = false;
          });
          // 用户认证失败后的处理逻辑
          print("Authentication failed.");
        },
        // 可选配置参数
        biometricsType: BiometricsType.all, // 可以选择 BiometricsType.fingerprint, BiometricsType.face 等
        cancelButtonText: 'Cancel',
        localizedReason: 'Please authenticate to continue',
        stickyAuth: true, // 是否保持认证状态,直到用户明确取消
      );

      if (!canAuthenticate) {
        // 如果设备不支持生物识别或者生物识别不可用
        setState(() {
          _isAuthenticated = false;
        });
        print("Biometrics are not available on this device.");
      }
    } catch (e) {
      // 处理异常
      print(e);
      setState(() {
        _isAuthenticated = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Biometrics Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You are authenticated: $_isAuthenticated',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _authenticate,
              child: Text('Authenticate'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个简单的 Flutter 应用,包含一个按钮和一个文本标签来显示用户的认证状态。
  2. _authenticate 方法调用 FlutterBiometrics.authenticate 来触发生物识别认证。
  3. 如果认证成功,authenticated 回调会被调用,并更新 _isAuthenticated 状态。
  4. 如果认证失败或设备不支持生物识别,相应的处理逻辑会在 failedcanAuthenticate 的结果中处理。

请确保在实际项目中处理所有可能的异常情况,并根据需要自定义认证界面的 UI 和逻辑。

回到顶部