qr.dart 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'dart:async' show Future;
  2. import '../config/routes.dart';
  3. import '../state/app_state.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/services.dart' show PlatformException;
  6. import '../l10n/app_localizations.dart';
  7. import '../ui/adaptive.dart' show AppScaffold, AdaptiveDialogAction;
  8. import 'package:barcode_scan2/barcode_scan2.dart' show BarcodeScanner;
  9. /// Page for adding accounts by scanning QR.
  10. class ScanQRPage extends StatefulWidget {
  11. const ScanQRPage({super.key});
  12. @override
  13. State<ScanQRPage> createState() => _ScanQRPageState();
  14. }
  15. class _ScanQRPageState extends State<ScanQRPage> {
  16. @override
  17. void initState() {
  18. super.initState();
  19. // Trigger scan
  20. WidgetsBinding.instance.addPostFrameCallback(
  21. (_) async {
  22. try {
  23. final value = await _scan();
  24. // Parse scanned value into item and pop
  25. var item = BaseItemType.newAuthenticatorItemFromUri(value);
  26. // Pop until scan page
  27. Navigator.of(context)
  28. .popUntil(ModalRoute.withName(AppRoutes.addScan));
  29. // Pop with scanned item
  30. Navigator.of(context).pop(item);
  31. } catch (e) {
  32. await showAdaptiveDialog(
  33. context: context,
  34. builder: (BuildContext context) {
  35. return AlertDialog.adaptive(
  36. title: Text(AppLocalizations.of(context)!.error),
  37. content: Text(e.toString()),
  38. actions: [
  39. AdaptiveDialogAction(
  40. child: Text(AppLocalizations.of(context)!.ok),
  41. onPressed: () {
  42. // Pop dialog
  43. Navigator.of(context).pop();
  44. },
  45. )
  46. ],
  47. );
  48. });
  49. Navigator.of(context)
  50. .popUntil(ModalRoute.withName(AppRoutes.addScan));
  51. Navigator.of(context).pop();
  52. }
  53. },
  54. );
  55. }
  56. @override
  57. Widget build(BuildContext context) {
  58. return AppScaffold(
  59. title: Text(AppLocalizations.of(context)!.addScanQR),
  60. body: const Center(),
  61. );
  62. }
  63. // Scans and returns scanned QR code
  64. // Adapted from documentation of flutter_barcode_reader
  65. Future _scan() async {
  66. try {
  67. var barcode = await BarcodeScanner.scan();
  68. return barcode.rawContent;
  69. } on PlatformException catch (e) {
  70. if (e.code == BarcodeScanner.cameraAccessDenied) {
  71. return Future.error(
  72. AppLocalizations.of(context)!.errNoCameraPermission);
  73. } else {
  74. return Future.error('${AppLocalizations.of(context)!.errUnknown} $e');
  75. }
  76. } on FormatException {
  77. return Future.error(AppLocalizations.of(context)!.errIncorrectFormat);
  78. } catch (e) {
  79. return Future.error('${AppLocalizations.of(context)!.errUnknown} $e');
  80. }
  81. }
  82. }