local_auth
此Flutter插件提供了對用戶執(zhí)行本地設(shè)備上身份驗證的方法
這意味著要參考IOS (Touch ID或lock code)上的生物識別認(rèn)證裆操,以及Android(在Android 6.0中引入)上的指紋api。
Dart中的用法
1 . 添加到庫
將其添加到項目的pubspec.yaml文件中:
此版本比較穩(wěn)定 沒有出現(xiàn)過問題
dependencies:
local_auth: ^0.6.1+3
2 .安裝
在項目中打開控制臺,執(zhí)行:
flutter packages get
3 .導(dǎo)入
在Dart代碼中晕翠,使用:
import 'package:local_auth/local_auth.dart';
4 .集成
iOS集成
請注意瞳浦,此插件適用于TouchID和FaceID担映。但是,要使用后者叫潦,還需要添加:
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
到Info.plist文件蝇完。如果不這樣做,會出現(xiàn)一個對話框,告訴用戶您的應(yīng)用尚未更新為使用TouchID短蜕。
Android集成
修改項目的AndroidManifest.xml文件以包含 USE_FINGERPRINT權(quán)限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<manifest>
具體用法
要檢查此設(shè)備上是否有可用的本地身份驗證氢架,請調(diào)用canCheckBiometrics:
bool canCheckBiometrics = await localAuth.canCheckBiometrics;
目前已實現(xiàn)以下生物識別類型:
- BiometricType.face (人臉識別)
- BiometricType.fingerprint (指紋識別)
要獲取已登記的生物識別列表,請調(diào)用getAvailableBiometrics:
List<BiometricType> availableBiometrics;
await auth.getAvailableBiometrics();
if (Platform.isIOS) {
if (availableBiometrics.contains(BiometricType.face)) {
// Face ID.
} else if (availableBiometrics.contains(BiometricType.fingerprint)) {
// Touch ID.
}
}
默認(rèn)對話框朋魔,其中包含“確定”按鈕岖研,可顯示以下兩種情況的身份驗證錯誤消息:
- 密碼/ PIN /模式未設(shè)置。用戶尚未在iOS上配置密碼或在Android上配置PIN /模式警检。
- Touch ID /指紋未注冊孙援。用戶尚未在設(shè)備上注冊任何指紋。
也就是說扇雕,如果用戶的設(shè)備上沒有指紋拓售,就會彈出一個帶有指令的對話框,讓用戶設(shè)置指紋镶奉。如果用戶點擊“確定”按鈕础淤,則返回“false”。
使用導(dǎo)出的API通過默認(rèn)對話框觸發(fā)本地身份驗證:
var localAuth = LocalAuthentication();
bool didAuthenticate =
await localAuth.authenticateWithBiometrics(
localizedReason: '請進行身份驗證以顯示帳戶余額');
如果您不想使用默認(rèn)對話框哨苛,請使用’ useerrordialog = false’調(diào)用此API鸽凶。在這種情況下,它會返回錯誤消息建峭,您需要在省道代碼中處理它們:
bool didAuthenticate =
await localAuth.authenticateWithBiometrics(
localizedReason: '請進行身份驗證以顯示帳戶余額',
useErrorDialogs: false);
可以使用默認(rèn)對話框消息玻侥,也可以通過傳入IOSAuthMessages和AndroidAuthMessages來使用自己的消息:
import 'package:local_auth/auth_strings.dart';
const andStrings = const AndroidAuthMessages(
cancelButton: '取消',
goToSettingsButton: '去設(shè)置',
fingerprintNotRecognized: '指紋識別失敗',
goToSettingsDescription: '請設(shè)置指紋.',
fingerprintHint: '指紋',
fingerprintSuccess: '指紋識別成功',
signInTitle: '指紋驗證',
fingerprintRequiredTitle: '請先錄入指紋!',
);
authenticated = await auth.authenticateWithBiometrics(
localizedReason: '掃描指紋進行身份驗證',
useErrorDialogs: false,
androidAuthStrings :andStrings,
/* iOSAuthStrings: iosStrings, */
stickyAuth: true
);
異常
異常有4種類型:PasscodeNotSet、notenroll迹缀、NotAvailable和OtherOperatingSystem使碾。它們被包裝在LocalAuthenticationError類中。您可以捕獲異常并按不同類型處理它們祝懂。例如:
import 'package:flutter/services.dart';
import 'package:local_auth/error_codes.dart' as auth_error;
try {
bool didAuthenticate = await local_auth.authenticateWithBiometrics(
localizedReason: '請進行身份驗證以顯示帳戶余額');
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
// 在這里處理這個異常票摇。
}
}
Sticky Auth
您可以將插件上的stickyAuth選項設(shè)置為true,以便當(dāng)系統(tǒng)將應(yīng)用程序放到后臺時插件不會返回失敗砚蓬。如果用戶在進行身份驗證之前接到電話矢门,就可能發(fā)生這種情況。如果stickyAuth設(shè)置為false灰蛙,將導(dǎo)致插件返回失敗結(jié)果給Dart應(yīng)用程序祟剔。如果設(shè)置為true,插件將在應(yīng)用程序恢復(fù)時重試身份驗證摩梧。
案例
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
/// 本地認(rèn)證框架
final LocalAuthentication auth = LocalAuthentication();
/// 是否有可用的生物識別技術(shù)
bool _canCheckBiometrics;
/// 生物識別技術(shù)列表
List<BiometricType> _availableBiometrics;
/// 識別結(jié)果
String _authorized = '驗證失敗';
/// 檢查是否有可用的生物識別技術(shù)
Future<Null> _checkBiometrics() async {
bool canCheckBiometrics;
try {
canCheckBiometrics = await auth.canCheckBiometrics;
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_canCheckBiometrics = canCheckBiometrics;
});
}
/// 獲取生物識別技術(shù)列表
Future<Null> _getAvailableBiometrics() async {
List<BiometricType> availableBiometrics;
try {
availableBiometrics = await auth.getAvailableBiometrics();
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_availableBiometrics = availableBiometrics;
});
}
/// 生物識別
Future<Null> _authenticate() async {
bool authenticated = false;
try {
authenticated = await auth.authenticateWithBiometrics(
localizedReason: '掃描指紋進行身份驗證',
useErrorDialogs: true,
stickyAuth: false);
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_authorized = authenticated ? '驗證通過' : '驗證失敗';
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件的示例應(yīng)用程序'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text('是否有可用的生物識別技術(shù): $_canCheckBiometrics\n'),
RaisedButton(
child: const Text('檢查生物識別技術(shù)'),
onPressed: _checkBiometrics,
),
Text('可用的生物識別技術(shù): $_availableBiometrics\n'),
RaisedButton(
child: const Text('獲取可用的生物識別技術(shù)'),
onPressed: _getAvailableBiometrics,
),
Text('狀態(tài): $_authorized\n'),
RaisedButton(
child: const Text('驗證'),
onPressed: _authenticate,
)
])),
));
}
}