qrvalidator.dart 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * QR.Flutter
  3. * Copyright (c) 2019 the QR.Flutter authors.
  4. * See LICENSE for distribution and usage details.
  5. */
  6. import 'package:qr/qr.dart';
  7. import 'package:flyinsonolite/controls/qrcode/qrversions.dart';
  8. /// A utility class for validating and pre-rendering QR code data.
  9. class QrValidator {
  10. /// Attempt to parse / generate the QR code data and check for any errors. The
  11. /// resulting [QrValidationResult] object will hold the status of the QR code
  12. /// as well as the generated QR code data.
  13. static QrValidationResult validate({
  14. required String data,
  15. int version = QrVersions.auto,
  16. int errorCorrectionLevel = QrErrorCorrectLevel.L,
  17. }) {
  18. late final QrCode qrCode;
  19. try {
  20. if (version != QrVersions.auto) {
  21. qrCode = QrCode(version, errorCorrectionLevel);
  22. qrCode.addData(data);
  23. } else {
  24. qrCode = QrCode.fromData(
  25. data: data,
  26. errorCorrectLevel: errorCorrectionLevel,
  27. );
  28. }
  29. return QrValidationResult(
  30. status: QrValidationStatus.valid, qrCode: qrCode);
  31. } on InputTooLongException catch (itle) {
  32. return QrValidationResult(
  33. status: QrValidationStatus.contentTooLong, error: itle);
  34. } on Exception catch (ex) {
  35. return QrValidationResult(status: QrValidationStatus.error, error: ex);
  36. }
  37. }
  38. }
  39. /// Captures the status or a QR code validation operations, as well as the
  40. /// rendered and validated data / object so that it can be used in any
  41. /// secondary operations (to avoid re-rendering). It also keeps any exception
  42. /// that was thrown.
  43. class QrValidationResult {
  44. /// Create a new validation result instance.
  45. QrValidationResult({required this.status, this.qrCode, this.error});
  46. /// The status of the validation operation.
  47. QrValidationStatus status;
  48. /// The rendered QR code data / object.
  49. QrCode? qrCode;
  50. /// The exception that was thrown in the event of a non-valid result (if any).
  51. Exception? error;
  52. /// The validation result returned a status of valid;
  53. bool get isValid => status == QrValidationStatus.valid;
  54. }
  55. /// The status of the QR code data you requested to be validated.
  56. enum QrValidationStatus {
  57. /// The QR code data is valid for the provided parameters.
  58. valid,
  59. /// The QR code data is too long for the provided version + error check
  60. /// configuration or too long to be contained in a QR code.
  61. contentTooLong,
  62. /// An unknown / unexpected error occurred when we tried to validate the QR
  63. /// code data.
  64. error,
  65. }