better_local_auth 0.0.1 copy "better_local_auth: ^0.0.1" to clipboard
better_local_auth: ^0.0.1 copied to clipboard

Enhanced local authentication plugin for biometrics with required cryptoObject support for Android security compliance.

example/lib/main.dart

// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:better_local_auth/better_local_auth.dart';

void main() {
  runApp(const BetterLocalAuthExampleApp());
}

class BetterLocalAuthExampleApp extends StatelessWidget {
  const BetterLocalAuthExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Better Local Auth Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const BetterLocalAuthExamplePage(),
    );
  }
}

class BetterLocalAuthExamplePage extends StatefulWidget {
  const BetterLocalAuthExamplePage({super.key});

  @override
  State<BetterLocalAuthExamplePage> createState() =>
      _BetterLocalAuthExamplePageState();
}

class _BetterLocalAuthExamplePageState
    extends State<BetterLocalAuthExamplePage> {
  final LocalAuthentication _localAuth = LocalAuthentication();
  final BetterLocalAuthentication _betterLocalAuth =
      BetterLocalAuthentication();
  String _authResult = 'Not authenticated';
  bool _isAuthenticating = false;

  Future<void> _authenticateWithBetterLocalAuth() async {
    if (_isAuthenticating) return;

    setState(() {
      _isAuthenticating = true;
      _authResult = 'Authenticating with enhanced API...';
    });

    try {
      // Use factory method from BetterLocalAuthentication
      final cryptoObject = BetterLocalAuthentication.createSignatureCryptoObject(
        keyAlias: 'example_app_key',
        dataToSign: Uint8List.fromList('example_data_to_sign'.codeUnits),
      );

      // Create keychain options for iOS
      final keychainOptions = KeychainOptions(
        serviceName: 'com.example.better_local_auth',
        accountName: 'example_user',
        accessibility: KeychainAccessibility.whenUnlockedThisDeviceOnly,
      );

      final AuthResult result = await _betterLocalAuth.authenticateEnhanced(
        localizedReason: 'Authenticate with enhanced security',
        cryptoObject: cryptoObject,
        keychainOptions: keychainOptions,
      );

      setState(() {
        _authResult = result.authenticated
            ? 'Enhanced authentication successful!'
            : 'Enhanced authentication failed';
      });
    } catch (e) {
      setState(() {
        _authResult = 'Error: $e';
      });
    } finally {
      setState(() {
        _isAuthenticating = false;
      });
    }
  }

  Future<void> _checkBiometrics() async {
    try {
      final bool canCheck = await _localAuth.canCheckBiometrics;
      final List<BiometricType> availableBiometrics =
          await _localAuth.getAvailableBiometrics();
      final bool isSupported = await _localAuth.isDeviceSupported();

      setState(() {
        _authResult =
            'Biometrics check:\n'
            '- Can check biometrics: $canCheck\n'
            '- Available biometrics: ${availableBiometrics.join(", ")}\n'
            '- Device supported: $isSupported';
      });
    } catch (e) {
      setState(() {
        _authResult = 'Error checking biometrics: $e';
      });
    }
  }

  Future<void> _showMigrationExample() async {
    final exampleCode = '''
// Old code using local_auth:
// import 'package:local_auth/local_auth.dart';
// final auth = LocalAuthentication();
// await auth.authenticate(localizedReason: 'Test');

// New code using better_local_auth:
import 'package:better_local_auth/better_local_auth.dart';
final auth = LocalAuthentication();

// Create required crypto object
final cryptoObject = CryptoObject.forSignature(
  keyAlias: 'my_app_key',
  data: Uint8List.fromList('data_to_sign'.codeUnits),
);

// Create required keychain options
final keychainOptions = KeychainOptions(
  serviceName: 'com.example.app',
  accountName: 'user_auth',
);

await auth.authenticate(
  localizedReason: 'Test',
  cryptoObject: cryptoObject,
  keychainOptions: keychainOptions,
);
''';

    // For this example, just show the code in the result
    setState(() {
      _authResult = 'Migration example:\n$exampleCode';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Better Local Auth Example'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              _authResult,
              style: Theme.of(context).textTheme.bodyLarge,
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed:
                  _isAuthenticating ? null : _authenticateWithBetterLocalAuth,
              child: const Text('Authenticate (BetterLocalAuthentication)'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _checkBiometrics,
              child: const Text('Check Biometrics'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _showMigrationExample,
              child: const Text('Show Migration Example'),
            ),
            const SizedBox(height: 20),
            if (_isAuthenticating)
              const CircularProgressIndicator(),
          ],
        ),
      ),
    );
  }
}
1
likes
0
points
199
downloads

Publisher

verified publisherjhonaiquel.com

Weekly Downloads

Enhanced local authentication plugin for biometrics with required cryptoObject support for Android security compliance.

Homepage

Topics

#authentication #biometrics #local-auth #security #crypto

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on better_local_auth

Packages that implement better_local_auth