Flutter本地认证iOS凭证管理插件local_auth_ios_credentials的使用
Flutter本地认证iOS凭证管理插件local_auth_ios_credentials
的使用
使用
此包是官方推荐插件的一部分,这意味着您可以直接使用local_auth
。当你这样做时,此包将自动包含在您的应用中。
示例代码
以下是一个完整的示例代码,展示了如何使用local_auth_ios_credentials
插件来实现本地认证功能。
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth_ios_credentials/local_auth_ios_credentials.dart';
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
_SupportState _supportState = _SupportState.unknown;
bool? _canCheckBiometrics;
List<BiometricType>? _enrolledBiometrics;
String _authorized = 'Not Authorized';
bool _isAuthenticating = false;
[@override](/user/override)
void initState() {
super.initState();
LocalAuthPlatform.instance.isDeviceSupported().then(
(bool isSupported) => setState(() => _supportState = isSupported
? _SupportState.supported
: _SupportState.unsupported),
);
}
Future<void> _checkBiometrics() async {
late bool deviceSupportsBiometrics;
try {
deviceSupportsBiometrics =
await LocalAuthPlatform.instance.deviceSupportsBiometrics();
} on PlatformException catch (e) {
deviceSupportsBiometrics = false;
print(e);
}
if (!mounted) {
return;
}
setState(() {
_canCheckBiometrics = deviceSupportsBiometrics;
});
}
Future<void> _getEnrolledBiometrics() async {
late List<BiometricType> enrolledBiometrics;
try {
enrolledBiometrics =
await LocalAuthPlatform.instance.getEnrolledBiometrics();
} on PlatformException catch (e) {
enrolledBiometrics = <BiometricType>[];
print(e);
}
if (!mounted) {
return;
}
setState(() {
_enrolledBiometrics = enrolledBiometrics;
});
}
Future<void> _authenticate() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await LocalAuthPlatform.instance.authenticate(
localizedReason: 'Let OS determine authentication method',
authMessages: <AuthMessages>[const IOSAuthMessages()],
options: const AuthenticationOptions(
stickyAuth: true,
),
);
setState(() {
_isAuthenticating = false;
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
setState(
() => _authorized = authenticated ? 'Authorized' : 'Not Authorized');
}
Future<void> _authenticateWithBiometrics() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await LocalAuthPlatform.instance.authenticate(
localizedReason:
'Scan your fingerprint (or face or whatever) to authenticate',
authMessages: <AuthMessages>[const IOSAuthMessages()],
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
setState(() {
_isAuthenticating = false;
_authorized = 'Authenticating';
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
final String message = authenticated ? 'Authorized' : 'Not Authorized';
setState(() {
_authorized = message;
});
}
Future<void> _cancelAuthentication() async {
await LocalAuthPlatform.instance.stopAuthentication();
setState(() => _isAuthenticating = false);
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
padding: const EdgeInsets.only(top: 30),
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_supportState == _SupportState.unknown)
const CircularProgressIndicator()
else if (_supportState == _SupportState.supported)
const Text('This device is supported')
else
const Text('This device is not supported'),
const Divider(height: 100),
Text('Device supports biometrics: $_canCheckBiometrics\n'),
ElevatedButton(
onPressed: _checkBiometrics,
child: const Text('Check biometrics'),
),
const Divider(height: 100),
Text('Enrolled biometrics: $_enrolledBiometrics\n'),
ElevatedButton(
onPressed: _getEnrolledBiometrics,
child: const Text('Get enrolled biometrics'),
),
const Divider(height: 100),
Text('Current State: $_authorized\n'),
if (_isAuthenticating)
ElevatedButton(
onPressed: _cancelAuthentication,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Cancel Authentication'),
Icon(Icons.cancel),
],
),
)
else
Column(
children: <Widget>[
ElevatedButton(
onPressed: _authenticate,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Authenticate'),
Icon(Icons.perm_device_information),
],
),
),
ElevatedButton(
onPressed: _authenticateWithBiometrics,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(_isAuthenticating
? 'Cancel'
: 'Authenticate: biometrics only'),
const Icon(Icons.fingerprint),
],
),
),
],
),
],
),
],
),
),
);
}
}
enum _SupportState {
unknown,
supported,
unsupported,
}
更多关于Flutter本地认证iOS凭证管理插件local_auth_ios_credentials的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter本地认证iOS凭证管理插件local_auth_ios_credentials的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
local_auth_ios_credentials
是一个 Flutter 插件,用于管理 iOS 设备上的本地认证凭证。它允许你与 iOS 的本地认证系统(如 Touch ID 和 Face ID)进行交互,管理用户的生物识别认证凭证。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 local_auth_ios_credentials
插件的依赖:
dependencies:
flutter:
sdk: flutter
local_auth_ios_credentials: ^0.0.1
然后运行 flutter pub get
来安装插件。
使用插件
local_auth_ios_credentials
插件提供了一些方法来管理 iOS 设备上的本地认证凭证。以下是基本的使用方法:
1. 检查设备是否支持生物识别认证
在使用 local_auth_ios_credentials
之前,你可以使用 local_auth
插件来检查设备是否支持生物识别认证(如 Touch ID 或 Face ID)。
import 'package:local_auth/local_auth.dart';
final localAuth = LocalAuthentication();
Future<bool> checkBiometrics() async {
bool canCheckBiometrics = await localAuth.canCheckBiometrics;
return canCheckBiometrics;
}
2. 管理凭证
local_auth_ios_credentials
插件提供了以下方法来管理凭证:
- 获取凭证列表: 获取设备上存储的所有本地认证凭证。
- 添加凭证: 向设备添加一个新的本地认证凭证。
- 删除凭证: 从设备中删除一个本地认证凭证。
import 'package:local_auth_ios_credentials/local_auth_ios_credentials.dart';
final localAuthCredentials = LocalAuthIosCredentials();
// 获取凭证列表
Future<List<String>> getCredentials() async {
List<String> credentials = await localAuthCredentials.getCredentials();
return credentials;
}
// 添加凭证
Future<void> addCredential(String credential) async {
await localAuthCredentials.addCredential(credential);
}
// 删除凭证
Future<void> deleteCredential(String credential) async {
await localAuthCredentials.deleteCredential(credential);
}
3. 示例代码
以下是一个完整的示例,展示了如何使用 local_auth_ios_credentials
插件来管理 iOS 设备上的本地认证凭证:
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_ios_credentials/local_auth_ios_credentials.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocalAuthScreen(),
);
}
}
class LocalAuthScreen extends StatefulWidget {
@override
_LocalAuthScreenState createState() => _LocalAuthScreenState();
}
class _LocalAuthScreenState extends State<LocalAuthScreen> {
final LocalAuthentication localAuth = LocalAuthentication();
final LocalAuthIosCredentials localAuthCredentials = LocalAuthIosCredentials();
List<String> credentials = [];
@override
void initState() {
super.initState();
_checkBiometrics();
_getCredentials();
}
Future<void> _checkBiometrics() async {
bool canCheckBiometrics = await localAuth.canCheckBiometrics;
if (canCheckBiometrics) {
print("设备支持生物识别认证");
} else {
print("设备不支持生物识别认证");
}
}
Future<void> _getCredentials() async {
credentials = await localAuthCredentials.getCredentials();
setState(() {});
}
Future<void> _addCredential() async {
await localAuthCredentials.addCredential("new_credential");
_getCredentials();
}
Future<void> _deleteCredential(String credential) async {
await localAuthCredentials.deleteCredential(credential);
_getCredentials();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Local Auth iOS Credentials'),
),
body: ListView.builder(
itemCount: credentials.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(credentials[index]),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () => _deleteCredential(credentials[index]),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _addCredential,
child: Icon(Icons.add),
),
);
}
}
注意事项
-
iOS 权限: 在使用生物识别认证时,确保在
Info.plist
文件中添加了适当的权限声明。例如:<key>NSFaceIDUsageDescription</key> <string>我们需要使用 Face ID 来进行身份验证</string>