Skip to content

Commit ea4ba77

Browse files
authored
Fix null _nextFrame in MultiFrameImageStreamCompleter._handleAppFrame when a listener is re-added (flutter#193575)
**Title:** Fix null `_nextFrame` in `MultiFrameImageStreamCompleter._handleAppFrame` when a listener is re-added --- `MultiFrameImageStreamCompleter._handleAppFrame` can run after its decoded frame has been thrown away. When that happens it dereferences a null `_nextFrame`. In debug builds this fails the `_nextFrame != null` assertion; in release builds it throws `Null check operator used on a null value`. ### How it happens 1. A frame is decoded and `_handleAppFrame` is scheduled as a frame callback. 2. Before that frame runs, the stream drops to zero listeners and a listener is added back. `_ImageState` does this whenever `TickerMode` changes, for example during a route push or pop. Something must keep the completer alive while it has no listeners, as `ImageCache` does. 3. `removeListener` cancels only `_timer`. It does not cancel the pending frame callback. 4. `addListener` calls `_decodeNextFrameAndSchedule()`. That synchronously disposes `_nextFrame` and sets it to null before it awaits the next frame. 5. The pending `_handleAppFrame` then runs with listeners present and `_nextFrame == null`. flutter#30346 fixed flutter#30340 by stopping `_handleAppFrame` from being registered twice (`_frameCallbackScheduled`). It did not handle the callback that is already pending when decoding restarts; that PR's test for this scenario was merged disabled. The same failure was reported again in flutter#122576. ### Fix `_handleAppFrame` now returns early when `_nextFrame` is null. The restarted decode sets `_nextFrame` and calls `_scheduleAppFrame()` when it completes. `_frameCallbackScheduled` has already been reset at that point, so the animation resumes on the next frame. The only visible effect is one skipped animation frame instead of an exception. This follows the same pattern as the `_codec == null` check added in flutter#165009. We see this crash in production in several apps that treat framework errors as fatal. The trigger is animated images that are on screen during route transitions. ### Tests Adds `re-adding a listener while a frame callback is pending does not crash` to `image_stream_test.dart`. It reproduces the race without depending on timing: - Without the fix it fails with `Failed assertion: line 1064 pos 12: '_nextFrame != null'`. - With the fix it passes, and the animation resumes once the restarted decode completes. - All other tests in `image_stream_test.dart` still pass. Fixes flutter#30340 Related: flutter#122576, flutter#30346 ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. <!-- Keep the checklist link references from the upstream PR template. -->
1 parent 12b69d6 commit ea4ba77

2 files changed

Lines changed: 66 additions & 1 deletion

File tree

‎packages/flutter/lib/src/painting/image_stream.dart‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1061,7 +1061,13 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter {
10611061
if (!hasListeners) {
10621062
return;
10631063
}
1064-
assert(_nextFrame != null);
1064+
// A listener can be re-added after this callback was scheduled (for
1065+
// example when TickerMode toggles during a route transition). That
1066+
// restarts decoding in addListener, which discards _nextFrame. The
1067+
// in-flight decode schedules a new callback when it completes.
1068+
if (_nextFrame == null) {
1069+
return;
1070+
}
10651071
if (_isFirstFrame() || _hasFrameDurationPassed(timestamp)) {
10661072
_emitFrame(
10671073
ImageInfo(image: _nextFrame!.image.clone(), scale: _scale, debugLabel: debugLabel),

‎packages/flutter/test/painting/image_stream_test.dart‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,65 @@ void main() {
576576
imageCache.clear();
577577
});
578578

579+
testWidgets('re-adding a listener while a frame callback is pending does not crash', (
580+
WidgetTester tester,
581+
) async {
582+
// Regression test for https://github.com/flutter/flutter/issues/30340.
583+
final mockCodec = MockCodec();
584+
mockCodec.frameCount = 2;
585+
mockCodec.repetitionCount = -1;
586+
final codecCompleter = Completer<Codec>();
587+
588+
final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter(
589+
codec: codecCompleter.future,
590+
scale: 1.0,
591+
);
592+
593+
final emittedImages = <ImageInfo>[];
594+
addTearDown(() {
595+
for (final image in emittedImages) {
596+
image.dispose();
597+
}
598+
});
599+
final listener = ImageStreamListener((ImageInfo image, bool synchronousCall) {
600+
emittedImages.add(image);
601+
});
602+
imageStream.addListener(listener);
603+
// Mirrors ImageCache keeping the completer alive with zero listeners.
604+
final ImageStreamCompleterHandle handle = imageStream.keepAlive();
605+
606+
codecCompleter.complete(mockCodec);
607+
await tester.idle();
608+
609+
// Decoding the first frame schedules a frame callback.
610+
mockCodec.completeNextFrame(FakeFrameInfo(const Duration(milliseconds: 200), image20x10));
611+
await tester.idle();
612+
expect(mockCodec.numFramesAsked, 1);
613+
614+
// Before that callback runs, drop to zero listeners and re-add one, as
615+
// _ImageState does when TickerMode toggles. This restarts decoding and
616+
// discards the decoded frame.
617+
imageStream.removeListener(listener);
618+
imageStream.addListener(listener);
619+
expect(mockCodec.numFramesAsked, 2);
620+
621+
// The stale callback must not touch the discarded frame.
622+
await tester.pump();
623+
expect(tester.takeException(), isNull);
624+
expect(emittedImages, isEmpty);
625+
626+
// When the restarted decode completes, the animation resumes.
627+
mockCodec.completeNextFrame(FakeFrameInfo(const Duration(milliseconds: 200), image200x100));
628+
await tester.idle();
629+
await tester.pump();
630+
expect(emittedImages, hasLength(1));
631+
expect(emittedImages.single.image.width, 200);
632+
633+
handle.dispose();
634+
imageStream.removeListener(listener);
635+
imageCache.clear();
636+
});
637+
579638
testWidgets('multiple stream listeners', (WidgetTester tester) async {
580639
final mockCodec = MockCodec();
581640
mockCodec.frameCount = 2;

0 commit comments

Comments
 (0)