Mobile development · Intermediate · 26 min
Write Flutter unit, widget and golden tests
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14.0 · mocktail 1.0.5
You will have a small Flutter 3.50 clinic app covered by unit tests, widget tests with a mocktail fake repository and golden image tests, plus an on-device integration test ready to run.
On this page
Flutter gives you three kinds of automated test, and each one answers a different question. A unit test asks whether a plain Dart function or class gives the right answer. A widget test builds part of your interface on a simulated screen, taps and types into it, and asks whether it reacts correctly. A golden test draws a widget to a PNG file and fails when a later change alters a single pixel. Unit and widget tests run in seconds with flutter test on any laptop or CI machine. Integration tests run the whole app on a real device or emulator and are slower, so you keep fewer of them.
In this tutorial you build a small clinic services app with testing in mind: the business rules sit in plain Dart, the screen loads its services through a repository you can replace, and every list row has a clear label for screen readers. Then you test it at each level. You fake the repository with mocktail to check the loading spinner, the error state and the retry button, you record goldens of a row with a long Swahili name and of the whole screen at the width of a budget Android phone, and you learn why golden files belong to one pinned CI image rather than to everyone's laptop.
The app is new and self-contained, so you do not need the project from earlier tutorials.
Step 1 · Create the project and add mocktail
Check the SDK first:
flutter --versionThe first line should start with Flutter 3.50.1 (or a later 3.50 release) on the stable channel, with Dart 3.14 below it. Golden files depend on the exact Flutter version, so note this number; step 6 comes back to it.
Create a phone-only project in a practice folder, add mocktail as a development dependency, and remove the starter test, which tests the counter app you are about to replace:
mkdir -p ~/flutter-tests-demo
cd ~/flutter-tests-demo
flutter create --platforms=android,ios clinic_checks
cd clinic_checks
flutter pub add dev:mocktail:^1.0.5
rm test/widget_test.dartThe dev: prefix puts mocktail under dev_dependencies in pubspec.yaml, so it is available to tests but never shipped inside the app. flutter create already lists flutter_test, the SDK package that provides testWidgets, the finders and the golden matcher. It also adds material_ui to dependencies: since Flutter 3.47 the Material widgets live in that package, and importing package:flutter/material.dart is deprecated, so every file in this tutorial imports package:material_ui/material_ui.dart instead.
Check it worked
cd ~/flutter-tests-demo/clinic_checks
grep -nE '^ (flutter_test|flutter_lints|mocktail):' pubspec.yaml
grep -q '^ mocktail: \^1.0.5' pubspec.yaml
ls testThe first grep prints three numbered lines: flutter_test:, then flutter_lints: with its version, then mocktail: ^1.0.5 last, because flutter pub add appends to the end of dev_dependencies. The second grep prints nothing and only fails if the mocktail line is missing. ls test prints nothing because the folder is now empty.
Step 2 · Keep the rules in plain Dart and unit-test them
Code that does not touch widgets is the cheapest code to test, so pull the rules of the screen out into plain Dart. The app needs three: a service list, a basket of selected services that totals their time, and a search filter. Write the data first:
cd ~/flutter-tests-demo/clinic_checks
cat > lib/services.dart <<'DART'
class ClinicService {
const ClinicService({
required this.id,
required this.name,
required this.minutes,
});
final String id;
final String name;
final int minutes;
}
const clinicServices = <ClinicService>[
ClinicService(id: 'gp', name: 'GP consultation', minutes: 15),
ClinicService(id: 'bp', name: 'Blood pressure check', minutes: 10),
ClinicService(
id: 'antenatal',
name: 'Ushauri wa lishe kwa akina mama wajawazito',
minutes: 30,
),
ClinicService(id: 'malaria', name: 'Malaria rapid test', minutes: 15),
ClinicService(id: 'child-vaccines', name: 'Childhood vaccinations', minutes: 20),
ClinicService(id: 'eyes', name: 'Eye test', minutes: 30),
ClinicService(id: 'therapy', name: 'Talking therapy', minutes: 50),
ClinicService(id: 'travel-vaccines', name: 'Travel vaccines', minutes: 30),
];
DARTThen the rules:
cd ~/flutter-tests-demo/clinic_checks
cat > lib/basket.dart <<'DART'
import 'package:clinic_checks/services.dart';
/// Formats a number of minutes as "45 min", "1 h" or "1 h 5 min".
String formatDuration(int minutes) {
if (minutes < 0) {
throw ArgumentError.value(minutes, 'minutes', 'must not be negative');
}
final hours = minutes ~/ 60;
final rest = minutes % 60;
if (hours == 0) {
return '$rest min';
}
if (rest == 0) {
return '$hours h';
}
return '$hours h $rest min';
}
/// The services a patient has picked. Each change returns a new basket.
class Basket {
const Basket([this.ids = const <String>{}]);
final Set<String> ids;
Basket toggle(String id) {
if (ids.contains(id)) {
return Basket({...ids}..remove(id));
}
return Basket({...ids, id});
}
int totalMinutes(List<ClinicService> services) {
return services
.where((service) => ids.contains(service.id))
.fold(0, (total, service) => total + service.minutes);
}
}
/// Services whose name contains the query, ignoring case and outer spaces.
List<ClinicService> filterServices(List<ClinicService> services, String query) {
final needle = query.trim().toLowerCase();
if (needle.isEmpty) {
return services;
}
return services
.where((service) => service.name.toLowerCase().contains(needle))
.toList();
}
DARTNow the unit tests. In a pure Dart package you would depend on package:test; in a Flutter project, flutter_test re-exports the same test, group, setUp and expect functions, so one import covers both kinds of test:
cd ~/flutter-tests-demo/clinic_checks
cat > test/basket_test.dart <<'DART'
import 'package:clinic_checks/basket.dart';
import 'package:clinic_checks/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('formatDuration', () {
test('shows minutes under an hour', () {
expect(formatDuration(0), '0 min');
expect(formatDuration(45), '45 min');
});
test('shows whole hours without minutes', () {
expect(formatDuration(60), '1 h');
expect(formatDuration(120), '2 h');
});
test('shows hours and minutes together', () {
expect(formatDuration(65), '1 h 5 min');
});
test('rejects negative numbers', () {
expect(() => formatDuration(-5), throwsArgumentError);
});
});
group('Basket', () {
test('toggle adds a service and a second toggle removes it', () {
const empty = Basket();
final once = empty.toggle('gp');
expect(once.ids, {'gp'});
expect(once.toggle('gp').ids, isEmpty);
expect(empty.ids, isEmpty, reason: 'the original basket is unchanged');
});
test('totalMinutes adds up only the selected services', () {
final basket = const Basket().toggle('gp').toggle('therapy');
expect(basket.totalMinutes(clinicServices), 65);
expect(formatDuration(basket.totalMinutes(clinicServices)), '1 h 5 min');
});
});
group('filterServices', () {
test('matches part of a name in any case', () {
final names = filterServices(clinicServices, ' VACC ')
.map((service) => service.name);
expect(names, ['Childhood vaccinations', 'Travel vaccines']);
});
test('returns everything for an empty query', () {
expect(filterServices(clinicServices, ''), hasLength(8));
});
});
}
DART
flutter test test/basket_test.dartEach test names one behaviour in plain words, so a failure reads like a broken promise: "formatDuration shows whole hours without minutes". group adds the prefix. The reason argument on expect adds your own explanation to the failure message.
Check it worked
The run ends with All tests passed! and a +8 count. Change '1 h 5 min' in the third formatDuration test to '1 h 05 min' and run flutter test test/basket_test.dart again: it fails, printing Expected: '1 h 05 min' and Actual: '1 h 5 min'. Change it back before you continue.
Step 3 · Build the screen behind a repository
A widget test should not depend on a network, a database or a clock you cannot control. The usual fix is a repository: an interface that the screen asks for data, with a real version in the app and a fake one in tests. Write the interface and the version the app uses:
cd ~/flutter-tests-demo/clinic_checks
cat > lib/service_repository.dart <<'DART'
import 'package:clinic_checks/services.dart';
abstract interface class ServiceRepository {
Future<List<ClinicService>> fetchServices();
}
/// Serves the built-in list. A real app would call its API here.
class InMemoryServiceRepository implements ServiceRepository {
const InMemoryServiceRepository();
@override
Future<List<ClinicService>> fetchServices() async => clinicServices;
}
DART
cat > lib/theme.dart <<'DART'
import 'package:material_ui/material_ui.dart';
ThemeData clinicTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
brightness: brightness,
),
);
}
DARTThe theme lives in its own function so the app and the golden tests draw with exactly the same colours. Next, one row of the list:
cd ~/flutter-tests-demo/clinic_checks
cat > lib/service_tile.dart <<'DART'
import 'package:clinic_checks/basket.dart';
import 'package:clinic_checks/services.dart';
import 'package:material_ui/material_ui.dart';
class ServiceTile extends StatelessWidget {
const ServiceTile({
super.key,
required this.service,
required this.selected,
required this.onTap,
});
final ClinicService service;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final colours = Theme.of(context).colorScheme;
return Semantics(
container: true,
excludeSemantics: true,
button: true,
selected: selected,
label: '${service.name}, ${service.minutes} minutes',
onTap: onTap,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Expanded(
child: Text(
service.name,
style: Theme.of(context).textTheme.titleMedium,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 12),
Text(formatDuration(service.minutes)),
const SizedBox(width: 8),
Icon(
selected ? Icons.check_circle : Icons.radio_button_unchecked,
color: selected ? colours.primary : colours.outline,
),
],
),
),
),
);
}
}
DARTThe Semantics wrapper gives each row one clear announcement for TalkBack and VoiceOver, such as "GP consultation, 15 minutes", instead of three separate fragments, and says whether the row is selected. container: true gives the row its own node in the semantics tree, and excludeSemantics: true drops the fragments underneath it. Your widget tests use that same label to find the row, so a test that passes also proves the label is there.
Now the screen. It loads services once, shows a spinner while it waits, shows an error with a retry button if loading fails, and otherwise shows a search field, a summary and the list:
cd ~/flutter-tests-demo/clinic_checks
cat > lib/services_screen.dart <<'DART'
import 'package:clinic_checks/basket.dart';
import 'package:clinic_checks/service_repository.dart';
import 'package:clinic_checks/service_tile.dart';
import 'package:clinic_checks/services.dart';
import 'package:material_ui/material_ui.dart';
class ServicesScreen extends StatefulWidget {
const ServicesScreen({super.key, required this.repository});
final ServiceRepository repository;
@override
State<ServicesScreen> createState() => _ServicesScreenState();
}
class _ServicesScreenState extends State<ServicesScreen> {
late Future<List<ClinicService>> _services;
Basket _basket = const Basket();
String _query = '';
@override
void initState() {
super.initState();
_services = widget.repository.fetchServices();
}
void _retry() {
setState(() {
_services = widget.repository.fetchServices();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Clinic services')),
body: FutureBuilder<List<ClinicService>>(
future: _services,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Could not load services'),
const SizedBox(height: 12),
FilledButton(
onPressed: _retry,
child: const Text('Try again'),
),
],
),
);
}
final all = snapshot.requireData;
final shown = filterServices(all, _query);
final minutes = formatDuration(_basket.totalMinutes(all));
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: TextField(
decoration: const InputDecoration(
labelText: 'Search services',
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
),
onChanged: (value) => setState(() => _query = value),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Align(
alignment: Alignment.centerLeft,
child: Text('${_basket.ids.length} selected · $minutes'),
),
),
const Divider(height: 1),
Expanded(
child: shown.isEmpty
? const Center(child: Text('No services match'))
: ListView.builder(
itemCount: shown.length,
itemBuilder: (context, index) {
final service = shown[index];
return ServiceTile(
service: service,
selected: _basket.ids.contains(service.id),
onTap: () => setState(() {
_basket = _basket.toggle(service.id);
}),
);
},
),
),
],
);
},
),
);
}
}
DART
cat > lib/main.dart <<'DART'
import 'package:clinic_checks/service_repository.dart';
import 'package:clinic_checks/services_screen.dart';
import 'package:clinic_checks/theme.dart';
import 'package:material_ui/material_ui.dart';
void main() {
runApp(const ClinicApp(repository: InMemoryServiceRepository()));
}
class ClinicApp extends StatelessWidget {
const ClinicApp({super.key, required this.repository});
final ServiceRepository repository;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Clinic services',
theme: clinicTheme(Brightness.light),
darkTheme: clinicTheme(Brightness.dark),
home: ServicesScreen(repository: repository),
);
}
}
DARTThe screen never creates its own repository. It takes one through its constructor, so main.dart passes the in-memory version and a test can pass anything that implements ServiceRepository. The future is stored in initState rather than created inside build, because build runs on every setState and would start a new load each time you tap a row.
Check it worked
cd ~/flutter-tests-demo/clinic_checks
flutter analyzeThe analyser ends with No issues found!. If you have a device or emulator, flutter run shows a teal app bar, a search field, 0 selected · 0 min and eight services; tapping two of them changes the summary.
Step 4 · Test the screen with WidgetTester and a mocktail fake
A widget test runs your widgets in a test binding with a simulated 800 by 600 screen and a fake clock. Nothing appears on your monitor and nothing moves until you say so: pumpWidget builds the first frame, pump builds one more frame, and pumpAndSettle keeps building frames until there are no more animations or rebuilds scheduled.
mocktail creates the fake repository. A class that extends Mock and implements your interface answers every call with whatever you set up with when, and records the calls so you can check them with verify:
cd ~/flutter-tests-demo/clinic_checks
cat > test/services_screen_test.dart <<'DART'
import 'dart:async';
import 'package:clinic_checks/service_repository.dart';
import 'package:clinic_checks/service_tile.dart';
import 'package:clinic_checks/services.dart';
import 'package:clinic_checks/services_screen.dart';
import 'package:clinic_checks/theme.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:mocktail/mocktail.dart';
class MockServiceRepository extends Mock implements ServiceRepository {}
Widget appWith(ServiceRepository repository) {
return MaterialApp(
theme: clinicTheme(Brightness.light),
home: ServicesScreen(repository: repository),
);
}
void main() {
late MockServiceRepository repository;
setUp(() {
repository = MockServiceRepository();
});
testWidgets('shows a spinner until the services arrive', (tester) async {
final pending = Completer<List<ClinicService>>();
when(() => repository.fetchServices()).thenAnswer((_) => pending.future);
await tester.pumpWidget(appWith(repository));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(find.byType(ListView), findsNothing);
pending.complete(clinicServices);
await tester.pumpAndSettle();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.byType(ListView), findsOneWidget);
expect(find.text('0 selected · 0 min'), findsOneWidget);
verify(() => repository.fetchServices()).called(1);
});
testWidgets('tapping rows updates the summary', (tester) async {
when(() => repository.fetchServices())
.thenAnswer((_) async => clinicServices);
await tester.pumpWidget(appWith(repository));
await tester.pumpAndSettle();
await tester.tap(find.bySemanticsLabel('GP consultation, 15 minutes'));
await tester.pump();
expect(find.text('1 selected · 15 min'), findsOneWidget);
await tester.tap(find.bySemanticsLabel(RegExp('^Blood pressure check')));
await tester.pump();
expect(find.text('2 selected · 25 min'), findsOneWidget);
});
testWidgets('typing in the search field filters the list', (tester) async {
when(() => repository.fetchServices())
.thenAnswer((_) async => clinicServices);
await tester.pumpWidget(appWith(repository));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'vacc');
await tester.pump();
expect(find.byType(ServiceTile), findsNWidgets(2));
expect(find.text('Travel vaccines'), findsOneWidget);
expect(find.text('GP consultation'), findsNothing);
await tester.enterText(find.byType(TextField), 'dentist');
await tester.pump();
expect(find.text('No services match'), findsOneWidget);
});
testWidgets('shows an error and loads again on retry', (tester) async {
when(() => repository.fetchServices())
.thenAnswer((_) async => throw Exception('No connection'));
await tester.pumpWidget(appWith(repository));
await tester.pumpAndSettle();
expect(find.text('Could not load services'), findsOneWidget);
when(() => repository.fetchServices())
.thenAnswer((_) async => clinicServices);
await tester.tap(find.widgetWithText(FilledButton, 'Try again'));
await tester.pumpAndSettle();
expect(find.text('Could not load services'), findsNothing);
expect(find.byType(ListView), findsOneWidget);
verify(() => repository.fetchServices()).called(2);
});
}
DART
flutter test test/services_screen_test.dartSome details worth reading slowly:
- The first test hands the screen a
Completer's future, which stays unfinished until the test callscomplete. That is how you freeze an app in its loading state long enough to check the spinner. CallingpumpAndSettlebeforecompletewould fail withpumpAndSettle timed out, because a spinning progress indicator schedules a new frame forever. Usepumpwhile anything animates indefinitely. find.byTypefinds widgets by class,find.textby the exact string shown, andfind.widgetWithTextby a widget that contains some text, which picks out the right button when the same word appears elsewhere.find.bySemanticsLabellooks in the semantics tree that screen readers use, and accepts a string or aRegExp. If someone deletes theSemanticswrapper from the tile, this test fails, which is a cheap guard for accessibility.enterTextfocuses the field and replaces its text, which firesonChangedexactly as typing would.- The error test re-stubs
fetchServicesbetween the two calls, so the first load fails and the retry succeeds, andverify(...).called(2)proves the button really asked again.
Check it worked
The run ends with All tests passed! and +4. To see a useful failure, delete excludeSemantics: true, from lib/service_tile.dart and run flutter test test/services_screen_test.dart again: the tapping test fails because the row's label is no longer exactly "GP consultation, 15 minutes". Put the line back and run the tests once more before you continue.
Step 5 · Record and compare golden images
Widget tests check what is there; goldens check what it looks like. matchesGoldenFile draws a widget to an image and compares it with a PNG stored next to your tests. Tag the golden tests so you can run them, or skip them, on their own. Declare the tag once in dart_test.yaml at the project root:
cd ~/flutter-tests-demo/clinic_checks
cat > dart_test.yaml <<'YAML'
tags:
golden: {}
YAMLThen write three goldens: a row with the long Swahili name, a selected row, and the full screen at 360 by 720, close to the logical size of many low-cost Android phones:
cd ~/flutter-tests-demo/clinic_checks
cat > test/goldens_test.dart <<'DART'
@Tags(['golden'])
library;
import 'package:clinic_checks/service_repository.dart';
import 'package:clinic_checks/service_tile.dart';
import 'package:clinic_checks/services.dart';
import 'package:clinic_checks/services_screen.dart';
import 'package:clinic_checks/theme.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:mocktail/mocktail.dart';
class MockServiceRepository extends Mock implements ServiceRepository {}
Widget tileOnCanvas(ClinicService service, {required bool selected}) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: clinicTheme(Brightness.light),
home: Scaffold(
body: Center(
child: RepaintBoundary(
child: SizedBox(
width: 320,
child: ServiceTile(
service: service,
selected: selected,
onTap: () {},
),
),
),
),
),
);
}
void main() {
final longName = clinicServices.firstWhere((s) => s.id == 'antenatal');
testWidgets('a long name wraps inside the row', (tester) async {
await tester.pumpWidget(tileOnCanvas(longName, selected: false));
await expectLater(
find.byType(ServiceTile),
matchesGoldenFile('goldens/service_tile_long_name.png'),
);
});
testWidgets('a selected row shows the filled tick', (tester) async {
await tester.pumpWidget(tileOnCanvas(clinicServices.first, selected: true));
await expectLater(
find.byType(ServiceTile),
matchesGoldenFile('goldens/service_tile_selected.png'),
);
});
testWidgets('the whole screen at 360 by 720', (tester) async {
tester.view.physicalSize = const Size(360, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final repository = MockServiceRepository();
when(() => repository.fetchServices())
.thenAnswer((_) async => clinicServices);
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: clinicTheme(Brightness.light),
home: ServicesScreen(repository: repository),
),
);
await tester.pumpAndSettle();
await expectLater(
find.byType(ServicesScreen),
matchesGoldenFile('goldens/services_screen.png'),
);
});
}
DART@Tags(['golden']) on the library; line tags every test in the file. The matcher captures the nearest RepaintBoundary above the widget you find, which is why the tile sits inside one with a fixed width: the image is exactly one row, 320 pixels wide. For the screen, there is no boundary of your own, so the capture is the whole simulated display. The paths are relative to the test file, so the PNGs land in test/goldens/. The banner is switched off because the debug ribbon would otherwise sit in the corner of every screen image.
There are no golden files yet, so a normal run would fail with Could not be compared against non-existent file. Create them with --update-goldens, then run again without it to compare:
cd ~/flutter-tests-demo/clinic_checks
flutter test --tags golden --update-goldens
ls test/goldens
flutter test --tags goldenA failed comparison writes four images to test/failures/: the stored golden (masterImage), what the test drew (testImage), the differing pixels on their own (isolatedDiff) and those pixels laid over the original (maskedDiff). They are for you to look at, never to commit, so ignore the folder in Git:
cd ~/flutter-tests-demo/clinic_checks
printf '\n# Golden test diffs\ntest/failures/\n' >> .gitignore
grep -n 'test/failures/' .gitignoreCheck it worked
ls test/goldens lists service_tile_long_name.png, service_tile_selected.png and services_screen.png, and the second run ends with All tests passed! and +3. Open service_tile_long_name.png: the name runs onto two lines and is cut off with an ellipsis, because only about ten square test glyphs fit on each line of the 320 px tile and maxLines: 2 stops it there. Every letter is a solid rectangle. That is deliberate. Tests draw text with a built-in test font of square glyphs, so the image records layout, sizes and colours without depending on fonts installed on the machine.
Now watch one fail. In lib/theme.dart, change Colors.teal to Colors.indigo, then run flutter test --tags golden. All three goldens fail with Pixel test failed, a percentage and a pixel count, and test/failures/ holds the four images for each one. Change the colour back, delete test/failures, and run the command again to see it pass. When you change a design on purpose, rerun with --update-goldens and review the new PNGs in your pull request like any other change.
Step 6 · Pin goldens to one image in CI
The goldens you just made match your Flutter version on your operating system. Draw the same widget on macOS, Windows and Linux and the results are close but not identical: edges are anti-aliased slightly differently, and the Flutter documentation warns that a new Flutter version can change the output on the same machine too. By default any pixel that differs fails the test, so a golden recorded on one developer's Mac fails on a Linux CI runner for reasons nobody can see.
Teams avoid that with one rule: goldens are recorded and compared in a single, pinned environment, usually the same Linux image the CI job uses, with the Flutter version fixed in it. Everything else follows from that rule:
- CI runs the whole suite, goldens included, in that image.
- On laptops, developers run everything except the goldens. The tag you added makes that one flag:
cd ~/flutter-tests-demo/clinic_checks
flutter test --exclude-tags golden- When a design changes on purpose, someone refreshes the goldens inside the pinned image, not on their own machine, and commits the new PNGs. With Docker that looks like the command below; replace
your-registry/flutter-ci:3.50.1with your team's CI image:
docker run --rm -v "$PWD":/app -w /app your-registry/flutter-ci:3.50.1 flutter test --tags golden --update-goldens- A Flutter upgrade is its own pull request: bump the version in the image, regenerate every golden in one go, and review the diffs before merging, so a design change never hides inside an upgrade.
The test font helps here too. Because text is drawn as squares, the images do not depend on which fonts happen to be installed, which removes the largest source of drift. If you load your real fonts into golden tests to make the images readable, expect them to be even more sensitive to platform and version, and keep them inside the pinned image.
Check it worked
cd ~/flutter-tests-demo/clinic_checks
flutter testflutter test --exclude-tags golden ends with +12 (eight unit tests and four widget tests) and never opens a PNG, and the full flutter test ends with +15 and All tests passed!. Both counts come from the same files, so the only difference is the golden tag.
Step 7 · Add an integration test for a real device
Widget tests stop at the edge of Flutter: they never start Android or iOS, never draw with the device's real GPU and never call platform plugins. An integration test runs your actual app on a phone, emulator or simulator and drives it with the same WidgetTester API. Add the SDK's integration_test package as a development dependency:
cd ~/flutter-tests-demo/clinic_checks
flutter pub add 'dev:integration_test:{"sdk":"flutter"}'Integration tests live in their own integration_test folder, outside test, so flutter test on its own does not try to run them without a device:
cd ~/flutter-tests-demo/clinic_checks
mkdir -p integration_test
cat > integration_test/app_test.dart <<'DART'
import 'package:clinic_checks/main.dart';
import 'package:clinic_checks/service_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:material_ui/material_ui.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('a patient finds and picks a service', (tester) async {
await tester.pumpWidget(
const ClinicApp(repository: InMemoryServiceRepository()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'malaria');
await tester.pumpAndSettle();
await tester.tap(find.bySemanticsLabel(RegExp('^Malaria rapid test')));
await tester.pumpAndSettle();
expect(find.text('1 selected · 15 min'), findsOneWidget);
});
}
DART
flutter analyzeIntegrationTestWidgetsFlutterBinding.ensureInitialized() swaps the simulated test binding for one that drives the real app and reports results back to your terminal. The test itself reads just like a widget test, but here it uses the real ClinicApp with its real repository, which is the point: it checks that the pieces are wired together.
With a phone or emulator connected, run it:
cd ~/flutter-tests-demo/clinic_checks
flutter test integration_test/app_test.dartFlutter builds the app, installs it on the device, runs the test and prints the result. That takes minutes, not seconds, so keep integration tests to a few journeys that matter most and leave the detail to widget tests. If your users are mostly on entry-level Android phones, keep one such phone for this purpose: an emulator on a fast laptop hides the slow starts and dropped frames your users will meet.
Check it worked
flutter analyze ends with No issues found!, which proves the integration test compiles against your app. On a device, the run installs the app, you see the search field fill with "malaria" for a moment, and the terminal ends with All tests passed!.
Step 8 · Clean up
The next command deletes the practice project, including its tests and golden files. Keep it instead if you want to carry the tests into the state management or forms tutorials:
cd ~
rm -rf ~/flutter-tests-demoCheck it worked
ls ~/flutter-tests-demo reports that there is no such file or directory. The Flutter SDK in ~/develop/flutter and your pub cache are untouched.
Next steps
- Test forms the same way, entering text and checking validation errors: validate forms in Flutter.
- Swap the repository for a provider you can override in tests: manage app state in Flutter with Riverpod.
- Revisit how the rows, columns and lazy list you tested here are built: build Flutter screens from widgets, rows, columns and lists.
- Apply the same golden idea to websites: add visual regression tests with Playwright screenshots.
Part of these paths
Related tutorials
- Build Flutter screens from widgets, rows, columns and listsYou will build a clinic services screen in Flutter 3.50 from rows, columns and a lazy list, make taps update it with setState, theme it with Material 3 and prove it works at phone size with a widget test.
- Build and validate forms in FlutterYou will build a patient registration form in Flutter 3.50 with tested validation rules, the right keyboards and autofill, a date picker, errors that screen readers announce and a submit button that cannot be pressed twice.
- Add visual regression tests with Playwright screenshotsYou will have Playwright 1.65 screenshot tests for a page and a single card, with baselines committed to git, dynamic parts masked, a deliberate CSS change caught with a diff, and one Docker image that makes baselines match between your laptop and CI.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials