Flutter | GW アドベントカレンダーの5日目の記事です。
顔認証/指紋認証を実装するために、Flutter公式のlocal_authプラグインを使用します。
完成形
以下のような感じで、顔認証/指紋認証を実装します。
顔認証

指紋認証

Android

顔認証/指紋認証の実装
1. プラグインとの紐付け
pubspec.yaml
dependencies:
local_auth: ^0.4.0+1 // 追加
バージョンについては、local_authを参照してください。
2. 生体認証設定
iOSとAndroid側で以下を追加して、生体認証を行えるようにします。
iOS
info.plist
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
Android
AndroidManifest.xml
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
顔認証/指紋認証の実装
main.dart
import 'package:local_auth/local_auth.dart';
端末の可能な生体認証タイプを取得
main.dart
LocalAuthentication _localAuth = LocalAuthentication();
Future<List<BiometricType>> _getAvailableBiometricTypes() async {
List<BiometricType> availableBiometricTypes;
try {
availableBiometricTypes = await _localAuth.getAvailableBiometrics();
} on PlatformException catch (e) {
// TODO
}
return availableBiometricTypes;
}
生体認証を要求
main.dart
Future<bool> _authenticate() async {
bool result = false;
List<BiometricType> availableBiometricTypes = await _getAvailableBiometricTypes();
try {
if (availableBiometricTypes.contains(BiometricType.face)
|| availableBiometricTypes.contains(BiometricType.fingerprint)) {
result = await _localAuth.authenticateWithBiometrics(localizedReason: "認証してください");
}
} on PlatformException catch (e) {
// TODO
}
return result;
}
指紋/顔を登録していない場合の挙動は?
以下のように、登録を促すダイアログを自動的に表示してくれます。
ここで、顔や指紋を登録せずに「OK」ボタンを押された際には、認証結果がfalseで返ってきます。

Android
まとめ
local_authプラグインを実装しているだけです。
指紋認証も顔認証もかなり簡単に実装できてしまいます。
念のため、githubにプロジェクトおいています。
Flutterつよし!!!!