diff --git a/lib/src/blurhash_widget.dart b/lib/src/blurhash_widget.dart index ee24cbd..7030a3b 100644 --- a/lib/src/blurhash_widget.dart +++ b/lib/src/blurhash_widget.dart @@ -82,6 +82,16 @@ class BlurHashState extends State { late bool loaded; late bool loading; + /// The handle this state owns. Kept so it can be released, and so a decode + /// that lands after a newer one does not replace it. + ui.Image? _decoded; + int _decodeGeneration = 0; + + /// The image decoded from [BlurHash.hash], or null before the first decode + /// completes. + @visibleForTesting + ui.Image? get debugDecodedImage => _decoded; + @override void initState() { super.initState(); @@ -107,6 +117,7 @@ class BlurHashState extends State { } void _decodeImage() { + final generation = ++_decodeGeneration; _image = blurHashDecodeImage( blurHash: widget.hash, width: widget.decodingWidth, @@ -114,9 +125,25 @@ class BlurHashState extends State { optimizationMode: widget.optimizationMode, ); + _image.then((image) { + if (!mounted || generation != _decodeGeneration) { + image.dispose(); + return; + } + _decoded?.dispose(); + _decoded = image; + }).catchError((Object _) {}); + _image.whenComplete(() => widget.onDecoded?.call()); } + @override + void dispose() { + _decoded?.dispose(); + _decoded = null; + super.dispose(); + } + @override Widget build(BuildContext context) => Stack( fit: StackFit.expand, @@ -230,7 +257,11 @@ class UiImage extends ImageProvider { Future _loadAsync(UiImage key) async { assert(key == this); - return ImageInfo(image: image, scale: key.scale); + // An ImageStreamCompleter owns and disposes the ImageInfo it is given, so + // hand it a clone and keep our own handle. Sharing the handle makes the + // first cache eviction dispose the caller's image, and the next resolve of + // the same handle throws "Cannot clone a disposed image". + return ImageInfo(image: image.clone(), scale: key.scale); } @override diff --git a/test/blur_hash_dispose_test.dart b/test/blur_hash_dispose_test.dart new file mode 100644 index 0000000..251da55 --- /dev/null +++ b/test/blur_hash_dispose_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_blurhash/flutter_blurhash.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _hash = 'LGF5]+Yk^6#M@-5c,1J5@[or[Q6.'; + +Widget _host(Widget child, {required double devicePixelRatio}) => MediaQuery( + data: MediaQueryData( + devicePixelRatio: devicePixelRatio, + size: const Size(400, 800), + ), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox(width: 200, height: 200, child: child), + ), + ), + ); + +/// What PaintingBinding.handleMemoryPressure does when the platform reports +/// memory pressure. +Future _dropImageCache(WidgetTester tester) async { + PaintingBinding.instance.imageCache.clear(); + PaintingBinding.instance.imageCache.clearLiveImages(); + await tester.pump(); + await tester.idle(); + await tester.pump(); +} + +Future _settleDecode(WidgetTester tester) async { + await tester.runAsync(() => Future.delayed(const Duration(milliseconds: 50))); + await tester.pump(); +} + +void main() { + testWidgets('survives the image cache being dropped while mounted', + (WidgetTester tester) async { + final errors = []; + final previousOnError = FlutterError.onError; + FlutterError.onError = (details) => errors.add(details.exception); + + await tester.pumpWidget( + _host(const BlurHash(hash: _hash), devicePixelRatio: 2), + ); + await _settleDecode(tester); + + // Changing a dependency re-resolves the provider, which is what a rotation, + // a keyboard, a brightness change or a safe area inset does. + for (final devicePixelRatio in [3, 2, 3]) { + await _dropImageCache(tester); + await tester.pumpWidget( + _host(const BlurHash(hash: _hash), devicePixelRatio: devicePixelRatio), + ); + await _settleDecode(tester); + } + + FlutterError.onError = previousOnError; + expect(errors, isEmpty); + }); + + testWidgets('disposes the decoded image when it is unmounted', + (WidgetTester tester) async { + await tester.pumpWidget( + _host(const BlurHash(hash: _hash), devicePixelRatio: 2), + ); + await _settleDecode(tester); + + final state = tester.state(find.byType(BlurHash)); + final decoded = state.debugDecodedImage; + expect(decoded, isNotNull); + expect(decoded!.debugDisposed, isFalse); + + await tester.pumpWidget(_host(const SizedBox.shrink(), devicePixelRatio: 2)); + await tester.pump(); + + expect(decoded.debugDisposed, isTrue); + }); +}