Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion lib/src/blurhash_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ class BlurHashState extends State<BlurHash> {
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();
Expand All @@ -107,16 +117,33 @@ class BlurHashState extends State<BlurHash> {
}

void _decodeImage() {
final generation = ++_decodeGeneration;
_image = blurHashDecodeImage(
blurHash: widget.hash,
width: widget.decodingWidth,
height: widget.decodingHeight,
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,
Expand Down Expand Up @@ -230,7 +257,11 @@ class UiImage extends ImageProvider<UiImage> {

Future<ImageInfo> _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
Expand Down
78 changes: 78 additions & 0 deletions test/blur_hash_dispose_test.dart
Original file line number Diff line number Diff line change
@@ -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<void> _dropImageCache(WidgetTester tester) async {
PaintingBinding.instance.imageCache.clear();
PaintingBinding.instance.imageCache.clearLiveImages();
await tester.pump();
await tester.idle();
await tester.pump();
}

Future<void> _settleDecode(WidgetTester tester) async {
await tester.runAsync(() => Future<void>.delayed(const Duration(milliseconds: 50)));
await tester.pump();
}

void main() {
testWidgets('survives the image cache being dropped while mounted',
(WidgetTester tester) async {
final errors = <Object>[];
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 <double>[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<BlurHashState>(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);
});
}