Flutter本地身份验证插件common_local_authentication的使用

Flutter本地身份验证插件common_local_authentication的使用

在本教程中,我们将展示如何使用common_local_authentication插件来实现本地身份验证。该插件允许用户通过指纹或面部识别进行身份验证。

插件安装

首先,在您的pubspec.yaml文件中添加以下依赖项:

dependencies:
  common_authentication: ^1.0.0

然后运行以下命令以获取最新的包版本并更新pubspec.lock文件:

flutter pub get

使用示例

以下是使用common_local_authentication插件的完整示例代码:

示例代码

import 'dart:html';

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Authentication',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Authentication Example'),
    );
  }
}

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

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  // 控制器用于管理输入框的文本
  TextEditingController textEmailController = TextEditingController();
  TextEditingController textPasswordController = TextEditingController();

  // 初始化身份验证对象
  Authentication authentication = Authentication(apiUrl: "apiUrl");

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Form(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  /// 输入邮箱
                  TextFormField(
                    controller: textEmailController,
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    autocorrect: false,
                    style: const TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: Colors.black
                    ),
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                      hintStyle: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          color: Colors.grey
                      ),
                    ),
                  ),

                  /// 输入密码
                  TextFormField(
                    controller: textPasswordController,
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    autocorrect: false,
                    style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: Colors.black
                    ),
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                      hintStyle: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          color: Colors.grey
                      ),
                    ),
                  ),
                ],
              ),
            ),

            /// 登录按钮
            Align(
              alignment: Alignment.centerLeft,
              child: GestureDetector(
                onTap: () {
                  // 调用身份验证方法
                  authentication.authenticateUser(
                      email: textEmailController.text.toString(),
                      password: textPasswordController.text.toString()
                  );
                },
                child: Container(
                  margin: const EdgeInsets.only(left: 24, top: 24, bottom: 30, right: 24),
                  padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Container(
                    alignment: Alignment.center,
                    child: const Text(
                      "Login",
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                        fontSize: 16
                      ),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

更多关于Flutter本地身份验证插件common_local_authentication的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地身份验证插件common_local_authentication的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


common_local_authentication 是一个用于在 Flutter 应用中实现本地身份验证的插件。它允许开发者使用设备的生物识别(如指纹、面部识别)或 PIN/密码来进行用户身份验证。

以下是使用 common_local_authentication 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  common_local_authentication: ^1.0.0

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

2. 导入插件

在需要使用本地身份验证的 Dart 文件中导入插件:

import 'package:common_local_authentication/common_local_authentication.dart';

3. 检查设备是否支持身份验证

在进行身份验证之前,最好先检查设备是否支持生物识别或 PIN/密码验证:

bool isBiometricSupported = await CommonLocalAuthentication.isBiometricSupported();
bool isDeviceSupported = await CommonLocalAuthentication.isDeviceSupported();

if (isBiometricSupported) {
  print("设备支持生物识别");
} else if (isDeviceSupported) {
  print("设备支持 PIN/密码验证");
} else {
  print("设备不支持任何形式的本地身份验证");
}

4. 获取可用的生物识别类型

你可以获取设备支持的生物识别类型:

List<BiometricType> availableBiometrics = await CommonLocalAuthentication.getAvailableBiometrics();

if (availableBiometrics.contains(BiometricType.face)) {
  print("设备支持面部识别");
}
if (availableBiometrics.contains(BiometricType.fingerprint)) {
  print("设备支持指纹识别");
}

5. 执行身份验证

你可以使用 authenticate 方法来执行身份验证:

bool isAuthenticated = await CommonLocalAuthentication.authenticate(
  localizedReason: '请验证身份以继续',
  useErrorDialogs: true,
  stickyAuth: false,
);

if (isAuthenticated) {
  print("身份验证成功");
} else {
  print("身份验证失败");
}

6. 处理错误

在进行身份验证时,可能会遇到各种错误,例如用户取消验证或设备未设置生物识别。你可以使用 try-catch 块来捕获和处理这些错误:

try {
  bool isAuthenticated = await CommonLocalAuthentication.authenticate(
    localizedReason: '请验证身份以继续',
    useErrorDialogs: true,
    stickyAuth: false,
  );

  if (isAuthenticated) {
    print("身份验证成功");
  } else {
    print("身份验证失败");
  }
} catch (e) {
  print("身份验证过程中发生错误: $e");
}

7. 其他功能

common_local_authentication 插件还提供了一些其他功能,例如:

  • 取消身份验证:如果你希望在用户取消验证时执行某些操作,可以使用 cancelAuthentication 方法。
  • 检查生物识别是否已设置:你可以使用 isBiometricEnrolled 方法来检查用户是否已经设置了生物识别。
bool isBiometricEnrolled = await CommonLocalAuthentication.isBiometricEnrolled();

if (isBiometricEnrolled) {
  print("用户已设置生物识别");
} else {
  print("用户未设置生物识别");
}

8. 注意事项

  • 权限:在某些设备上,使用生物识别功能可能需要特定的权限。请确保在 AndroidManifest.xmlInfo.plist 中添加必要的权限声明。
  • 用户体验:在使用生物识别时,确保提供清晰的用户提示,并处理用户取消或验证失败的情况。

9. 示例代码

以下是一个完整的示例代码,展示了如何使用 common_local_authentication 插件进行本地身份验证:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('本地身份验证示例'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              try {
                bool isAuthenticated = await CommonLocalAuthentication.authenticate(
                  localizedReason: '请验证身份以继续',
                  useErrorDialogs: true,
                  stickyAuth: false,
                );

                if (isAuthenticated) {
                  print("身份验证成功");
                } else {
                  print("身份验证失败");
                }
              } catch (e) {
                print("身份验证过程中发生错误: $e");
              }
            },
            child: Text('验证身份'),
          ),
        ),
      ),
    );
  }
}
回到顶部