local_auth의 생물 측정을 사용해 보세요.

16926 단어 Fluttertech

개시하다


이번에는 플루터의 포장local_auth을 사용해 생물 측정을 실시하고 싶다.
이번에 사용한 판본은 다음과 같다.
  • Flutter 2.10.4
  • Dart 2.16.2

  • local_auth 2.0.0

  • hooks_riverpod : ^1.0.3
  • 설치하다.


    pubspec.yaml
      dependencies:
        local_auth: ^2.0.0 //追加
    

    기본 설정


    iOS 설정


    다음 설정을 추가합니다.
    Info.plist
      <key>NSFaceIDUsageDescription</key>
        <string>生体認証を使用する目的を記述</string>
    

    안드로이드 설정


    다음 코드를 추가합니다.
    MainActivity.kt
      import io.flutter.embedding.android.FlutterFragmentActivity
      import io.flutter.embedding.engine.FlutterEngine
      import io.flutter.plugins.GeneratedPluginRegistrant
    
      class MainActivity: FlutterFragmentActivity() {
        override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine)
         }
      }
    
    AndroidManifest.xml
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="com.example.app">
        <uses-permission android:name="android.permission.USE_FINGERPRINT"/> //追加
      <manifest>
    

    컨트롤러 생성


    다음과 같은 생물 측정 방법을 가진 컨트롤러를 만듭니다.
    ※ riverpod를 사용합니다.
    auth_controller.dart
    import 'package:hooks_riverpod/hooks_riverpod.dart';
    import 'package:local_auth/local_auth.dart';
    
    final localAuthenticationProvider = Provider<LocalAuthentication>(
      (ref) => LocalAuthentication(),
    );
    
    final authControllerProvider = Provider<AuthControllerProvider>(
      (ref) => AuthControllerProvider(ref.read),
    );
    
    class AuthControllerProvider {
      AuthControllerProvider(this._read);
    
      final Reader _read;
    
      LocalAuthentication get _auth => _read(localAuthenticationProvider);
    
      Future<bool> get canCheckBiometrics => _auth.canCheckBiometrics;
    
      Future<bool> didAuthenticate() async {
        final availableBiometrics = await _auth.getAvailableBiometrics();
        var result = false;
        if (availableBiometrics.contains(BiometricType.face) ||
            availableBiometrics.contains(BiometricType.fingerprint)) {
          result = await _auth.authenticate(
            localizedReason: 'Please authenticate to show account balance',
            options: const AuthenticationOptions(
              useErrorDialogs: true,
              stickyAuth: true,
              biometricOnly: true,
            ),
          );
        }
        return result;
      }
    }
    

    방법 세부 사항


    단말기에 사용 가능한 생물 측정 방법이 탑재되었는지 확인하다.
    //参考: final localAuth = LocalAuthentication();
    
    bool canCheckBiometrics = await localAuth.canCheckBiometrics
    
    생물 측정이 가능한 종류(얼굴 인증, 지문 인증)를 획득하는 방법.
    //参考: final auth = LocalAuthentication()
    
    List<BiometricsType> availableBiometrics = await auth.getAvailableBiometrics();
    
    //BiometricsTypeは生体認証が利用可能であれば、BiometricsType.faceかBiometricsType.fingerprintを返す
    //どれも使用できない場合は空の配列を返す
    
    인증을 수행하는 방법.
    //参考: final localAuth = LocalAuthentication();
    
    bool didAuthenticate = await localAuth.authenticate(
    localizedReason: ‘認証を実行してください。’,
    //optionで指定 biometricsOnly: true, 生体認証のみを利用する場合trueにする。
    );
    

    생물 측정을 집행하다


    방금 정의한 방법을 호출합니다.호출을 통해 생물 측정을 집행할 수 있다.
    home_page.dart
    class HomePage extends ConsumerWidget {
      const HomePage({Key? key}) : super(key: key);
    
      
      Widget build(BuildContext context, WidgetRef ref) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('local_auth'),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: () async {
    	  //生体認証を実行
                await ref.read(authControllerProvider).didAuthenticate();
              },
              child: const Text('生体認証'),
            ),
          ),
        );
      }
    }
    

    끝맺다


    만약 보도에 잘못된 정보가 있다면 평론에서 지적해 주십시오.잘 부탁드립니다.

    좋은 웹페이지 즐겨찾기