How to test Image widgets source path in Flutter

2,458

Check what the image provider is with the image property of the Image widget class. From there you can extract individual properties:

String source;
if(image.image is AssetImage) {
  source = image.image.assetName;
} else if(image.image is NetworkImage) {
  source = image.image.url;
}

You could expand his to include more possible image providers as needed.

Share:
2,458
Joel Broström
Author by

Joel Broström

Updated on December 27, 2022

Comments

  • Joel Broström
    Joel Broström over 1 year

    I have the following setup:

    return Container(
          child: widget.searchResult.companyLogoUrl.isEmpty
              ? Image.asset('assets/images/missing-company-logo.png')
              : Image.network(widget.searchResult.companyLogoUrl),
        )
    

    And now I want to test that the missing logo image is loaded when no url is provided. How can I get the source url or local file after obtain the Image widget in a test?

    testWidgets('given', (tester) async {
          await tester.pumpWidget(createSearchResultCard(mockResponse));
          await tester.pumpAndSettle();
          final Image image = find.byType(Image).evaluate().single.widget as Image;
          final String source = image. // How do I get the file source?
          expect(...)
        });
    

    Is there a way to tell which picture has been loaded?

  • Joel Broström
    Joel Broström over 3 years
    It works. I had to typecast image.image once more in the if case, but after that it was smooth sailing.