paintcache.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * QR.Flutter
  3. * Copyright (c) 2019 the QR.Flutter authors.
  4. * See LICENSE for distribution and usage details.
  5. */
  6. import 'package:flutter/widgets.dart';
  7. import 'package:flyinsonolite/controls/qrcode/qrtypes.dart';
  8. ///
  9. class PaintCache {
  10. final List<Paint> _pixelPaints = <Paint>[];
  11. final Map<String, Paint> _keyedPaints = <String, Paint>{};
  12. String _cacheKey(QrCodeElement element, {FinderPatternPosition? position}) {
  13. final posKey = position != null ? position.toString() : 'any';
  14. return '${element.toString()}:$posKey';
  15. }
  16. /// Save a [Paint] for the provided element and position into the cache.
  17. void cache(Paint paint, QrCodeElement element,
  18. {FinderPatternPosition? position}) {
  19. if (element == QrCodeElement.codePixel) {
  20. _pixelPaints.add(paint);
  21. } else {
  22. _keyedPaints[_cacheKey(element, position: position)] = paint;
  23. }
  24. }
  25. /// Retrieve the first [Paint] object from the paint cache for the provided
  26. /// element and position.
  27. Paint? firstPaint(QrCodeElement element, {FinderPatternPosition? position}) {
  28. if (element == QrCodeElement.codePixel) {
  29. return _pixelPaints.first;
  30. } else {
  31. return _keyedPaints[_cacheKey(element, position: position)];
  32. }
  33. }
  34. /// Retrieve all [Paint] objects from the paint cache for the provided
  35. /// element and position. Note: Finder pattern elements can only have a max
  36. /// one [Paint] object per position. As such they will always return a [List]
  37. /// with a fixed size of `1`.
  38. List<Paint?> paints(QrCodeElement element,
  39. {FinderPatternPosition? position}) {
  40. if (element == QrCodeElement.codePixel) {
  41. return _pixelPaints;
  42. } else {
  43. return <Paint?>[_keyedPaints[_cacheKey(element, position: position)]];
  44. }
  45. }
  46. }