[030] 플러터 (Flutter) 배우기 - 아이폰 Face ID(페이스아이디,얼굴인식 구현하기)

2023. 2. 2. 16:13모바일어플개발/Flutter

반응형

안녕하세요~ totally 개발자입니다.

 

local_auth

 

오늘 구현해볼 것은 플러터 패키지 local_auth를 사용하여 아이폰에서의 Face ID를 구현해보려고 합니다. 아이패드 Face ID도 물론 가능합니다. 이 local_auth를 통해 지문 인식(touch ID)도 가능하며 ios뿐만 아니라 안드로이드도 지원합니다. 여기에서는 Face ID를 예제로 결과까지 보여드리도록 하겠습니다.

 

아래 패키지를 사용할 것이며 더 자세한 예시는 아래를 참고하시기 바랍니다.

https://pub.dev/packages/local_auth

 

local_auth | Flutter Package

Flutter plugin for Android and iOS devices to allow local authentication via fingerprint, touch ID, face ID, passcode, pin, or pattern.

pub.dev

 

Step 1: pubspec.yaml에 local_auth 추가

 

 

 

Step 2: 다음 사항들을 import 해줍니다.

import 'dart:async'; 

import 'package:flutter/material.dart'; 

import 'package:flutter/services.dart'; 

import 'package:local_auth/local_auth.dart';

 

 

Step 3: 아래 변수들을 선언해줍니다.

 

 

Step 4:  initState 내부에 auth.isDeviceSupported().then 함수를 아래처럼 적어줍니다.

 

Step 5: _authenticateWithBiometrics() async 함수를 명시해주시면 되며 아래 전체 코드를 첨부했고 위의 패키지 예제 페이지로 가서 복사하셔도 됩니다.

 

 

Step 6: _cancelAuthentication() async 메소드도 넣어줍니다.

 

Step 7: build 위젯입니다. 113번째 줄에 _authenticateWithBiometrics 함수를 호출하게 되며 Face ID가 가능한 아이폰 및 아이패드로 실행시 Face ID 인증 화면이 나오게 됩니다. 그리고 97번째 줄에 있는 $_authorized 변수와 setState 상태 업데이트를 통해 완료를 표시해주면 됩니다.

 

 

Step 8: 마지막으로 enum _SupportState도 정의해주면 됩니다.

 

Step 9: 시뮬레이터에서는 Face ID 인증하려고 하는 화면은 보이지만 실제로 구동이 되지는 않아서 제가 가지고 있는 아이폰으로 테스트해본 모습입니다.

[전체 소스 코드]

 

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
class TestView extends StatefulWidget {
@override
State<TestView> createState() => _TestViewState();
}
class _TestViewState extends State<TestView> {
final LocalAuthentication auth = LocalAuthentication();
_SupportState _supportState = _SupportState.unknown;
String _authorized = '인증되지 않음';
bool _isAuthenticating = false;
@override
void initState() {
super.initState();
auth.isDeviceSupported().then(
(bool isSupported) => setState(() => _supportState = isSupported
? _SupportState.supported
: _SupportState.unsupported),
);
}
Future<void> _authenticateWithBiometrics() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = '인증 진행 중...';
});
authenticated = await auth.authenticate(
localizedReason: '가능한 생체 인식으로 인증해주세요.',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
setState(() {
_isAuthenticating = false;
_authorized = '인증 진행 중...';
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = '오류 발생';
});
return;
}
if (!mounted) {
return;
}
final String message = authenticated ? '인증 완료' : '인증 실패';
setState(() {
_authorized = message;
});
}
Future<void> _cancelAuthentication() async {
await auth.stopAuthentication();
setState(() => _isAuthenticating = false);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Face ID 인증'),
),
body: ListView(
padding: const EdgeInsets.only(top: 30),
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_supportState == _SupportState.unknown)
const CircularProgressIndicator(
strokeWidth: 2,
)
else if (_supportState == _SupportState.supported)
Container(
padding: EdgeInsets.all(15),
child: Text("이 기기는 생체인식이 지원됩니다."),
)
else
Container(
padding: EdgeInsets.all(15),
child: Text("이 기기는 생체인식이 지원되지 않습니다."),
),
const Divider(height: 100),
Text('현재 인증 상태: $_authorized\n'),
if (_isAuthenticating)
ElevatedButton(
onPressed: _cancelAuthentication,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('인증 취소'),
Icon(Icons.cancel),
],
),
)
else
Column(
children: <Widget>[
ElevatedButton(
onPressed: _authenticateWithBiometrics,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(_isAuthenticating ? '취소하기' : 'Face ID로 인증하기'),
const Icon(Icons.face_outlined),
],
),
),
],
),
],
),
],
),
),
);
}
}
enum _SupportState {
unknown,
supported,
unsupported,
}
view raw 030.dart hosted with ❤ by GitHub

 

반응형