flutter 进行人脸以及指纹识别

1.插件:

local_auth: ^2.1.2

2.安卓配置

         2.1 在 MainActivity.kt 中,将原有的替换为:

package com.example.face

import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}

        2. 2修改默认主题:

        将 styles.xml中的  parent 替换为:

parent="Theme.AppCompat.Light.NoActionBar"

        2.3 添加权限:在 AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>

以上就是配置完成:

3.前提手机已经是配置了指纹或者人脸登录了,不然返回生物识别列表就是空的

注意:(就算是返回 BiometricType.strong  BiometricType.weak,没有  BiometricType.fingerprint  也是可以进行指纹或者是面容识别的 ,前面两者是指纹识别或者面容识别 )

一般的手机只能指纹登录,

这是因为Android10系统才开放面部识别

所以你的手机就算有面部解锁功能,调用这个Biometric库还是会调出指纹解锁。

还有一些手机即使是Android10也无法调用面部解锁,可能与厂商是否开放面部解锁功能有关。依赖

4.代码

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final LocalAuthentication _auth = LocalAuthentication();

  Future<bool> hasBiometrics() async {
    try {
      _auth.isDeviceSupported().then((value) {
        // print("设备支持");
        print(value);
      });
      // _auth.canCheckBiometrics;
      return await _auth.canCheckBiometrics;
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("hasBiometrics: $e");
      }
      return false;
    }
  }

  Future<List<BiometricType>> getBiometrics() async {
    try {
      return await _auth.getAvailableBiometrics();
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("getBiometrics: $e");
      }
      return <BiometricType>[];
    }
  }

  Future<bool> authenticate() async {
    final isAvailable = await hasBiometrics();
    if (!isAvailable) return false;
    try {
      return await _auth.authenticate(
          localizedReason: '请进行指纹识别',
          options: const AuthenticationOptions(
              biometricOnly: true, useErrorDialogs: true, stickyAuth: true));
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("authenticate: $e");
      }
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('生物识别'),
      ),
      body: ConstrainedBox(
          constraints: const BoxConstraints.expand(),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ElevatedButton(
                  onPressed: () async {
                    final isAvailable = await hasBiometrics();
                    final biometrics = await getBiometrics();
                    final hasFingerprint =
                        biometrics.contains(BiometricType.fingerprint);
                    final hasFace = biometrics.contains(BiometricType.face);
                    showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                              title: const Text('是否支持生物识别'),
                              content: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  buildText("生物识别", isAvailable),
                                  buildText("指纹识别", hasFingerprint),
                                  buildText("脸部识别", hasFace),
                                ],
                              ),
                            ));
                  },
                  child: const Text('检查生物识别'),
                ),
                InkWell(
                  onTap: () async {
                    try {
                      List<BiometricType> availableBiometrics =
                          await _auth.getAvailableBiometrics();
                      print(availableBiometrics);
                    } catch (e) {
                      print(e);
                    }
                  },
                  child: Container(
                    height: 50,
                    width: 100,
                    color: Colors.pink,
                    child: Text("获取生物列表"),
                  ),
                ),
                ElevatedButton(
                  onPressed: () async {
                    final isAuthenticated = await authenticate();
                    if (isAuthenticated) {
                      if (kDebugMode) {
                        print("验证通过");
                      }
                    }
                  },
                  child: const Text('权限验证'),
                )
              ])),
    ));
  }

  Widget buildText(String text, bool checked) => Container(
        margin: const EdgeInsets.symmetric(vertical: 8),
        child: Row(
          children: [
            checked
                ? const Icon(Icons.check, color: Colors.green, size: 24)
                : const Icon(Icons.close, color: Colors.red, size: 24),
            const SizedBox(width: 12),
            Text(text, style: const TextStyle(fontSize: 24))
          ],
        ),
      );
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值