Skip to content

(Will PR) When resized network image has error, all future unrelated images using the same url will fail, even if the network becomes OK #127265

Description

@fzyzcjy

Some possible approaches

Approach 1: Add ImageCache.evictWhere((key) => ...) in addition to evict(...).

Approach 2: Let ImageCache automatically evict failed caches.

Approach 3: Add a cache key in addition to the current key.


Is there an existing issue for this?

Steps to reproduce

(I will PR for this bug)

Hi thanks for the Flutter framework! When resized network image has error, all future unrelated images using the same url will fail, even if the network becomes OK.

After digging into source code, the cause is as follows: Even if NetworkImage does call imageCache.evict(), it is using the wrong key when it is wrapped with a ResizedImage. In other words, it is imageCache.evict(instanceOfNetworkImage), while the real key is an instance of the ResizedImage.

The following reproducible sample, though seemingly quite lengthy, is indeed very simple: Copy-and-paste (and slightly simplify) the https://github.com/flutter/flutter/blob/master/packages/flutter/test/painting/image_provider_network_image_test.dart. Then, just modify one line:

    // final ImageProvider imageProvider = NetworkImage(nonconst('testing.url'));
    final ImageProvider imageProvider = ResizeImage(NetworkImage(nonconst('testing.url')), width: 5, height: 5);

i.e. Add a ResizeImage. Then the tests fail.

Run test.

Expected results

no error.

Actual results

has error.

Code sample

Code sample
import 'dart:async';
import 'dart:io';
import 'dart:ui' show Codec, FrameInfo;

import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  late _FakeHttpClient httpClient;

  setUp(() {
    httpClient = _FakeHttpClient();
    debugNetworkImageHttpClientProvider = () => httpClient;
  });

  tearDown(() {
    debugNetworkImageHttpClientProvider = null;
    PaintingBinding.instance.imageCache.clear();
    PaintingBinding.instance.imageCache.clearLiveImages();
  });

  test('Expect thrown exception with statusCode - evicts from cache and drains', () async {
    const int errorStatusCode = HttpStatus.notFound;
    const String requestUrl = 'foo-url';

    httpClient.request.response.statusCode = errorStatusCode;

    final Completer<dynamic> caughtError = Completer<dynamic>();

    // final ImageProvider imageProvider = NetworkImage(nonconst(requestUrl));
    final ImageProvider imageProvider = ResizeImage(NetworkImage(nonconst(requestUrl)), width: 5, height: 5);

    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);

    final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);

    expect(imageCache.pendingImageCount, 1);
    expect(imageCache.statusForKey(imageProvider).pending, true);

    result.addListener(
        ImageStreamListener((ImageInfo info, bool syncCall) {}, onError: (dynamic error, StackTrace? stackTrace) {
      caughtError.complete(error);
    }));

    final dynamic err = await caughtError.future;

    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);

    expect(
      err,
      isA<NetworkImageLoadException>()
          .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode)
          .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)),
    );
    expect(httpClient.request.response.drained, true);
  }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag.

  test('NetworkImage is evicted from cache on SocketException', () async {
    final _FakeHttpClient mockHttpClient = _FakeHttpClient();
    mockHttpClient.thrownError = const SocketException('test exception');
    debugNetworkImageHttpClientProvider = () => mockHttpClient;

    // final ImageProvider imageProvider = NetworkImage(nonconst('testing.url'));
    final ImageProvider imageProvider = ResizeImage(NetworkImage(nonconst('testing.url')), width: 5, height: 5);

    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);

    final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);

    expect(imageCache.pendingImageCount, 1);
    expect(imageCache.statusForKey(imageProvider).pending, true);
    final Completer<dynamic> caughtError = Completer<dynamic>();
    result.addListener(ImageStreamListener(
      (ImageInfo info, bool syncCall) {},
      onError: (dynamic error, StackTrace? stackTrace) {
        caughtError.complete(error);
      },
    ));

    final dynamic err = await caughtError.future;

    expect(err, isA<SocketException>());

    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);
    expect(imageCache.containsKey(result), isFalse);

    debugNetworkImageHttpClientProvider = null;
  }, skip: isBrowser); // [intended] Browser does not resolve images this way.
}

class _FakeHttpClient extends Fake implements HttpClient {
  final _FakeHttpClientRequest request = _FakeHttpClientRequest();
  Object? thrownError;

  @override
  Future<HttpClientRequest> getUrl(Uri url) async {
    if (thrownError != null) {
      throw thrownError!;
    }
    return request;
  }
}

class _FakeHttpClientRequest extends Fake implements HttpClientRequest {
  final _FakeHttpClientResponse response = _FakeHttpClientResponse();

  @override
  Future<HttpClientResponse> close() async {
    return response;
  }
}

class _FakeHttpClientResponse extends Fake implements HttpClientResponse {
  bool drained = false;

  @override
  int statusCode = HttpStatus.ok;

  @override
  int contentLength = 0;

  @override
  HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed;

  late List<List<int>> content;

  @override
  StreamSubscription<List<int>> listen(void Function(List<int> event)? onData,
      {Function? onError, void Function()? onDone, bool? cancelOnError}) {
    return Stream<List<int>>.fromIterable(content).listen(
      onData,
      onDone: onDone,
      onError: onError,
      cancelOnError: cancelOnError,
    );
  }

  @override
  Future<E> drain<E>([E? futureValue]) async {
    drained = true;
    return futureValue ?? futureValue as E; // Mirrors the implementation in Stream.
  }
}

class FakeCodec implements Codec {
  @override
  void dispose() {}

  @override
  int get frameCount => throw UnimplementedError();

  @override
  Future<FrameInfo> getNextFrame() {
    throw UnimplementedError();
  }

  @override
  int get repetitionCount => throw UnimplementedError();
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[Paste your output here]

Activity

  1. changed the title [-]When resized network image has error, all future unrelated images using the same url will fail, even if the network becomes OK[/-] [+](Will PR) When resized network image has error, all future unrelated images using the same url will fail, even if the network becomes OK[/+] on May 20, 2023
  2. danagbemava-nc commented on May 22, 2023

    @danagbemava-nc
    Member

    Reproducible using the test sample provided above.

    Both tests pass when the line with ResizeImage is commented out but they fail when the ResizeImage is wrapped around the NetworkImage as reported above.

    test logs
    package:matcher                                     expect
    package:flutter_test/src/widget_tester.dart 452:18  expect
    test/fail_test.dart 41:5                            main.<fn>
    Warning: At least one test in this suite creates an HttpClient. When
    running a test suite that uses TestWidgetsFlutterBinding, all HTTP
    requests will return status code 400, and no network request will
    actually be made. Any test expecting a real network connection and
    status code will fail.
    To test code that needs an HttpClient, provide your own HttpClient
    implementation to the code under test, so that your test can
    consistently provide a testable response to the code under test.
    
    Expected: <true>
      Actual: <false>
    
    
    
    package:matcher                                     expect
    package:flutter_test/src/widget_tester.dart 452:18  expect
    test/fail_test.dart 76:5                            main.<fn>
    
    Expected: <true>
      Actual: <false>
    
    
    
    flutter doctor -v
    [✓] Flutter (Channel stable, 3.10.1, on macOS 13.3.1 22E772610a darwin-arm64, locale en-GB)
        • Flutter version 3.10.1 on channel stable at /Users/nexus/dev/sdks/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision d3d8effc68 (5 days ago), 2023-05-16 17:59:05 -0700
        • Engine revision b4fb11214d
        • Dart version 3.0.1
        • DevTools version 2.23.1
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
        • Android SDK at /Users/nexus/Library/Android/sdk
        • Platform android-33, build-tools 33.0.0
        • Java binary at: /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9971841/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode-14.3.0.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.12.1
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9971841/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9862592/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.2)
        • IntelliJ at /Users/nexus/Applications/JetBrains Toolbox/IntelliJ IDEA Ultimate.app
        • Flutter plugin version 73.1.1
        • Dart plugin version 231.9065
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.2)
        • IntelliJ at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.9011.34/IntelliJ IDEA.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.1)
        • IntelliJ at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.8770.65/IntelliJ IDEA.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.78.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.64.0
    
    [✓] Connected device (3 available)
        • Dean’s iPad (mobile) • 00008103-000825C811E3401E • ios            • iOS 16.4.1 20E252
        • macOS (desktop)      • macos                     • darwin-arm64   • macOS 13.3.1 22E772610a darwin-arm64
        • Chrome (web)         • chrome                    • web-javascript • Google Chrome 113.0.5672.126
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    
    [!] Flutter (Channel master, 3.11.0-10.0.pre.44, on macOS 13.3.1 22E772610a darwin-arm64, locale en-GB)
        • Flutter version 3.11.0-10.0.pre.44 on channel master at /Users/nexus/dev/sdks/flutters
        ! Warning: `flutter` on your path resolves to /Users/nexus/dev/sdks/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutters. Consider adding /Users/nexus/dev/sdks/flutters/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/nexus/dev/sdks/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutters. Consider adding /Users/nexus/dev/sdks/flutters/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision ab573048e7 (2 days ago), 2023-05-20 11:32:26 -0400
        • Engine revision aac0919568
        • Dart version 3.1.0 (build 3.1.0-129.0.dev)
        • DevTools version 2.23.1
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
        • Android SDK at /Users/nexus/Library/Android/sdk
        • Platform android-33, build-tools 33.0.0
        • Java binary at: /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9971841/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode-14.3.0.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.12.1
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9971841/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.9862592/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.2)
        • IntelliJ at /Users/nexus/Applications/JetBrains Toolbox/IntelliJ IDEA Ultimate.app
        • Flutter plugin version 73.1.1
        • Dart plugin version 231.9065
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.2)
        • IntelliJ at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.9011.34/IntelliJ IDEA.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.1.1)
        • IntelliJ at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.8770.65/IntelliJ IDEA.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.78.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.64.0
    
    [✓] Connected device (3 available)
        • Dean’s iPad (mobile) • 00008103-000825C811E3401E • ios            • iOS 16.4.1 20E252
        • macOS (desktop)      • macos                     • darwin-arm64   • macOS 13.3.1 22E772610a darwin-arm64
        • Chrome (web)         • chrome                    • web-javascript • Google Chrome 113.0.5672.126
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
    
    
  3. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    a: imagesLoading, displaying, rendering images
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on May 22, 2023
  4. added
    P2Important issues not at the top of the work list
    on May 30, 2023
  5. added a commit that references this issue on Aug 21, 2023
    aeddab4
  6. github-actions commented on Sep 5, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  7. locked as resolved and limited conversation to collaborators on Sep 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2Important issues not at the top of the work lista: imagesLoading, displaying, rendering imagesfound in release: 3.10Found to occur in 3.10found in release: 3.11Found to occur in 3.11frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer versionteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions