keyri_v3 1.4.3 copy "keyri_v3: ^1.4.3" to clipboard
keyri_v3: ^1.4.3 copied to clipboard

outdated

Keyri QR Login plugin for Flutter. Provides Keyri SDK capabilities for secure and passwordless login.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:keyri_v3/keyri.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

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

const String appKey = "[Your app key here]"; // Change it before launch
const String? publicApiKey = null; // Change it before launch, optional
const String? serviceEncryptionKey = null; // Change it before launch, optional
const bool blockEmulatorDetection = true;
const String? publicUserId = null; // Change it before launch, optional

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Keyri Example',
        theme: ThemeData(primarySwatch: Colors.blue),
        home: const KeyriHomePage(title: 'Keyri Example'));
  }
}

class KeyriHomePage extends StatefulWidget {
  const KeyriHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<KeyriHomePage> createState() => _KeyriHomePageState();
}

class _KeyriHomePageState extends State<KeyriHomePage> {
  Keyri keyri = Keyri(appKey,
      publicApiKey: publicApiKey,
      serviceEncryptionKey: serviceEncryptionKey,
      blockEmulatorDetection: true);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            button(_easyKeyriAuth, 'Easy Keyri Auth'),
            button(_customUI, 'Custom UI')
          ],
        ),
      ),
    );
  }

  void _easyKeyriAuth() {
    keyri
        .easyKeyriAuth('Some payload', publicUserId: publicUserId)
        .then((authResult) => _onAuthResult(authResult == true ? true : false))
        .catchError((error, stackTrace) => _processError(error));
  }

  void _customUI() {
    Navigator.push(context,
        MaterialPageRoute(builder: (context) => const KeyriScannerAuthPage()));
  }

  void _processError(dynamic error) {
    if (error is PlatformException) {
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(error.message ?? "Error occurred")));
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(error.toString())));
    }
  }

  void _onAuthResult(bool result) {
    String text;
    if (result) {
      text = 'Successfully authenticated!';
    } else {
      text = 'Authentication failed';
    }

    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
  }

  Widget button(VoidCallback onPressedCallback, String text) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        foregroundColor: Colors.white,
        backgroundColor: Colors.deepPurple,
      ),
      onPressed: onPressedCallback,
      child: Text(text),
    );
  }
}

class KeyriScannerAuthPage extends StatefulWidget {
  const KeyriScannerAuthPage({Key? key}) : super(key: key);

  @override
  State<KeyriScannerAuthPage> createState() => _KeyriScannerAuthPageState();
}

class _KeyriScannerAuthPageState extends State<KeyriScannerAuthPage> {
  bool _isLoading = false;

  Keyri keyri = Keyri(appKey,
      publicApiKey: publicApiKey,
      serviceEncryptionKey: serviceEncryptionKey,
      blockEmulatorDetection: true);

  void onMobileScannerDetect(BarcodeCapture barcodes) {
    if (barcodes.barcodes.isNotEmpty && !_isLoading) {
      var barcode = barcodes.barcodes[0];

      if (barcode.rawValue == null) {
        debugPrint('Failed to scan Barcode');
        return;
      }

      final String? code = barcode.rawValue;
      debugPrint('Scanned barcode: $code');

      if (code == null) return;

      var sessionId = Uri.dataFromString(code).queryParameters['sessionId'];

      if (sessionId == null) return;

      setState(() {
        _isLoading = true;
      });

      _onReadSessionId(sessionId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: _isLoading
                ? const Center(
                    child: Column(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [CircularProgressIndicator()]))
                : MobileScanner(onDetect: onMobileScannerDetect),
          )
        ],
      ),
    );
  }

  Future<void> _onReadSessionId(String sessionId) async {
    keyri
        .initiateQrSession(sessionId, publicUserId: publicUserId)
        .then((session) => keyri
            .initializeDefaultConfirmationScreen('Some payload')
            .then((authResult) => _onAuthResult(authResult))
            .catchError((error, stackTrace) => _onError(error.toString())))
        .catchError((error, stackTrace) => _onError(error.toString()));
  }

  void _onError(String message) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));

    Future.delayed(const Duration(milliseconds: 2000), () {
      setState(() {
        _isLoading = false;
      });
    });
  }

  void _onAuthResult(bool result) {
    var successfullyAuthenticatedText = 'Successfully authenticated!';

    if (!result) {
      successfullyAuthenticatedText = 'Failed to authenticate';
    }

    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(successfullyAuthenticatedText)));

    setState(() {
      _isLoading = false;
    });
  }
}
1
likes
0
points
20
downloads

Publisher

verified publisherkeyri.com

Weekly Downloads

Keyri QR Login plugin for Flutter. Provides Keyri SDK capabilities for secure and passwordless login.

Homepage

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on keyri_v3

Packages that implement keyri_v3