Contents
Outline
In order to load external images in Flutter
, you need to use Image.network
. In this blog post, I will introduce how to use the run_with_network_images
package to test the widget that displays the image using Image.network
.
run_with_network_images package
When you test a widget that uses Image.network
, The 400
error occurs and the test fails. Image.network
uses HttpClient
of dart:io
, but dart:io
always returns 400
error in Flutter
widget test, so this problem occurs.
When you use the run_with_network_images
package in the test code of Flutter
, you can solve this problem.
Install run_with_network_images package
To install the run_with_network_images
package, execute the following command to install the run_with_network_images
.
flutter pub add --dev run_with_network_images
How to use run_with_network_images
In order to test the widget that uses Image.network
, you need to modify the test code as follows using the runWithNetworkImages
function of run_with_network_images
.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:run_with_network_images/run_with_network_images.dart';
void main() {
testWidgets('Network image is rendered in widget test', (
WidgetTester tester,
) async {
await runWithNetworkImages(() async {
await tester.pumpWidget(const MyApp());
final image = tester.widget<Image>(find.byType(Image));
expect(
(image.image as NetworkImage).url,
'https://dev-yakuza.posstree.com/assets/images/yakuza.jpg',
);
});
});
}
Simply wrap the test code of the widget that uses Image.network
with await runWithNetworkImages(() async {});
to avoid the 400
error.
Completed
Done! We’ve seen how to use the run_with_network_images
package to test the widget that uses Image.network
in Flutter
test code. If you use Image.network
, this problem always occurs, so I recommend using the run_with_network_images
package.
The run_with_network_images
package is a package I created. If you have any feedback or improvements, please let me know at the GitHub repository.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.