thumbnail_widget.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:flutter/material.dart';
  2. import 'package:myapp/core/thumbnail_cache.dart';
  3. import 'package:myapp/models/photo.dart';
  4. import 'package:myapp/core/constants.dart';
  5. class ThumbnailWidget extends StatefulWidget {
  6. final Photo photo;
  7. const ThumbnailWidget(
  8. this.photo, {
  9. Key key,
  10. }) : super(key: key);
  11. @override
  12. _ThumbnailWidgetState createState() => _ThumbnailWidgetState();
  13. }
  14. class _ThumbnailWidgetState extends State<ThumbnailWidget> {
  15. static final Widget loadingWidget = Container(
  16. alignment: Alignment.center,
  17. color: Colors.grey[500],
  18. );
  19. bool _loadedSmallThumbnail = false;
  20. bool _loadedLargeThumbnail = false;
  21. ImageProvider _imageProvider;
  22. @override
  23. Widget build(BuildContext context) {
  24. if (!_loadedSmallThumbnail && !_loadedLargeThumbnail) {
  25. final cachedSmallThumbnail =
  26. ThumbnailLruCache.get(widget.photo, THUMBNAIL_SMALL_SIZE);
  27. if (cachedSmallThumbnail != null) {
  28. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  29. _loadedSmallThumbnail = true;
  30. } else {
  31. widget.photo
  32. .getAsset()
  33. .thumbDataWithSize(THUMBNAIL_SMALL_SIZE, THUMBNAIL_SMALL_SIZE)
  34. .then((data) {
  35. if (mounted) {
  36. setState(() {
  37. if (data != null) {
  38. _imageProvider = Image.memory(data).image;
  39. }
  40. _loadedSmallThumbnail = true;
  41. });
  42. }
  43. ThumbnailLruCache.put(widget.photo, THUMBNAIL_SMALL_SIZE, data);
  44. });
  45. }
  46. }
  47. if (_imageProvider != null) {
  48. return Image(
  49. image: _imageProvider,
  50. gaplessPlayback: true,
  51. fit: BoxFit.cover,
  52. );
  53. } else {
  54. return loadingWidget;
  55. }
  56. }
  57. }