thumbnail_widget.dart 2.2 KB

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