text_layout_cache.dart 754 B

123456789101112131415161718192021222324252627
  1. import 'package:flutter/painting.dart';
  2. import 'package:quiver/collection.dart';
  3. class TextLayoutCache {
  4. final LruMap<TextSpan, TextPainter> _cache;
  5. final TextDirection textDirection;
  6. TextLayoutCache(this.textDirection, int maximumSize) : _cache = LruMap<TextSpan, TextPainter>(maximumSize: maximumSize);
  7. TextPainter getOrPerformLayout(TextSpan text) {
  8. final cachedPainter = _cache[text];
  9. if (cachedPainter != null) {
  10. return cachedPainter;
  11. } else {
  12. return _performAndCacheLayout(text);
  13. }
  14. }
  15. TextPainter _performAndCacheLayout(TextSpan text) {
  16. final textPainter = TextPainter(text: text, textDirection: textDirection);
  17. textPainter.layout();
  18. _cache[text] = textPainter;
  19. return textPainter;
  20. }
  21. }