Sub topic 9
Making tests deterministic and avoiding flakiness
This chapter assumes you can already write and run a basic integration test, locate widgets with finders, and use pump and pumpAndSettle. You should also be comfortable with Key and the widget tree. Here you will learn why integration tests fail intermittently and how to remove the usual causes.
What flaky means and why it costs you
A flaky test sometimes passes and sometimes fails against the same code. Integration tests are flaky more often than unit or widget tests because they run the real app on a real device. The app uses real timers, real plugins, real animations, and often a real network.
A flaky suite is worse than a small suite. Once developers see failures that vanish on retry, they stop trusting red results. Real regressions then get ignored.
A test is deterministic when the same inputs always produce the same result. To get there, control every input the test depends on: the data, the clock, the network, the device state, and the timing of frames.
Where flakiness comes from
Most flaky integration tests trace back to a short list of causes.
| Cause | Symptom | Main fix |
|---|---|---|
| Finding widgets by visible text or position | Fails after a copy change or on a different screen size | Stable `Key` values |
| Assertions that run before the UI updates | "Expected: one matching node, Actual: no matching nodes" | Pump or wait explicitly |
| `pumpAndSettle` on a screen that never settles | Timeout exception | Pump a fixed duration or wait for a condition |
| State left over from a previous test | Passes alone, fails in the full suite | Reset state in `setUp` |
| Live network or backend data | Fails when the server is slow or data changes | Fake or seed the data layer |
| Real time, dates and random values | Fails at midnight or on a different day | Inject a clock and a seeded random source |
| Shared device state, such as permissions dialogs | Fails on a fresh install only | Prepare the device before the run |
The rest of the chapter works through these in turn.
Use stable keys instead of text or position
Finding a widget with find.text('Submit') breaks when the label changes, when the app is localized, or when the same word appears twice. Finding by position or by widget type breaks when the layout changes.
Assign a Key to each widget that tests interact with, and keep the key stable across redesigns.
import 'package:flutter/material.dart';
class LoginForm extends StatelessWidget {
const LoginForm({super.key, required this.onSubmit});
final VoidCallback onSubmit;
@override
Widget build(BuildContext context) {
return Column(
children: [
const TextField(key: Key('email_field')),
ElevatedButton(
key: const Key('submit_button'),
onPressed: onSubmit,
child: const Text('Sign in'),
),
],
);
}
}A test then uses find.byKey(const Key('submit_button')). The button can be renamed "Log in" and the test still passes.
For widgets built in a list, give each item a key that includes its identity, such as Key('todo_item_42'). Do not use the item's index, because the index changes when the list is reordered.
Wait for the right thing
Most timing failures come from asserting before the app has finished its work. There are three tools, and each fits a different case.
tester.pump()renders one frame. Use it when you want to advance by a known step.tester.pump(const Duration(milliseconds: 300))advances the fake clock and renders a frame. Use it for a known animation length.tester.pumpAndSettle()keeps pumping until no frames are scheduled. Use it when the UI has a finite number of animations.
When pumpAndSettle times out
pumpAndSettle throws after its timeout (ten minutes by default) if frames keep being scheduled. A looping progress indicator, a repeating animation, or a periodic timer that calls setState will prevent the screen from ever settling.
For those screens, do not use pumpAndSettle. Pump a fixed amount, or wait for a condition.
A reusable wait helper
When the app does asynchronous work, such as loading from a database, the cleanest approach is to wait until a finder matches, with an upper limit. This helper polls in short steps and fails with a clear message.
import 'package:flutter_test/flutter_test.dart';
Future<void> pumpUntilFound(
WidgetTester tester,
Finder finder, {
Duration timeout = const Duration(seconds: 10),
Duration step = const Duration(milliseconds: 100),
}) async {
final end = DateTime.now().add(timeout);
while (DateTime.now().isBefore(end)) {
await tester.pump(step);
if (finder.evaluate().isNotEmpty) {
return;
}
}
throw TestFailure('Timed out after $timeout waiting for $finder');
}Use it in place of a blind pumpAndSettle when you are waiting for specific content:
await tester.tap(find.byKey(const Key('load_button')));
await pumpUntilFound(tester, find.byKey(const Key('result_list')));
expect(find.byKey(const Key('todo_item_1')), findsOneWidget);This helper uses the wall clock on purpose. In an integration test running on a device, the app does real asynchronous work, so real time passes while you wait. The helper tolerates a slow device up to the timeout and returns as soon as the content appears, so fast devices are not slowed down.
Control the data
A test that depends on a live backend inherits all of the backend's problems: latency, outages, and data that changes between runs. Decide where to cut the app at a boundary, and replace what is beyond it.
The usual cut point is a repository or service class that the UI reads through. If your app already passes dependencies in through constructors or a dependency-injection container, an integration test can start the app with fakes.
abstract class TodoRepository {
Future<List<String>> fetchTodos();
}
class FakeTodoRepository implements TodoRepository {
@override
Future<List<String>> fetchTodos() async => ['Buy milk', 'Write tests'];
}To start the real app with the fake, expose an entry point that accepts dependencies. Here runApp receives a widget that takes the repository as a parameter:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/app.dart';
import 'package:my_app/todo_repository.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('shows seeded todos', (tester) async {
await tester.pumpWidget(MyApp(repository: FakeTodoRepository()));
await tester.pumpAndSettle();
expect(find.text('Buy milk'), findsOneWidget);
expect(find.text('Write tests'), findsOneWidget);
});
}This still runs the real widgets, real rendering, and real device. Only the data source is controlled. Some teams keep one small set of tests against a staging backend to catch contract changes, and run it separately from the main suite so its failures do not hide UI regressions.
Time and randomness
Code that calls DateTime.now() or Random() directly cannot be controlled from a test. Pass a clock function or a seeded Random into the code instead.
class Greeting {
Greeting({DateTime Function()? now}) : _now = now ?? DateTime.now;
final DateTime Function() _now;
String message() => _now().hour < 12 ? 'Good morning' : 'Good afternoon';
}A test passes now: () => DateTime(2026, 1, 1, 9) and always gets "Good morning", whatever time the suite runs. For random values, Random(42) always produces the same sequence.
Reset state between tests
Integration tests run inside one app process unless you restart it. State from one test, such as a logged-in user, saved preferences, or a pushed route, can leak into the next. A test then passes when run alone and fails in the full suite, or the reverse.
Reset what the app persists at the start of each test. With shared_preferences, for example, you can install a clean set of values:
import 'package:shared_preferences/shared_preferences.dart';
setUp(() async {
SharedPreferences.setMockInitialValues({});
});setMockInitialValues replaces the stored values for the app code running in the test. For other storage such as SQLite files or secure storage, delete the data in setUp through the same API the app uses. Also watch for in-memory singletons: if your app holds one in a global variable, create a fresh one per test or add a reset method.
Another approach is to launch the app freshly in every test by calling your entry point, and to make sure that entry point rebuilds all state. Starting from a new widget tree with pumpWidget is cheaper than restarting the process, but it does not clear global state, so reset globals explicitly.
Prepare the device
Some nondeterminism lives outside your code.
- Permission dialogs. The first run on a fresh install may show a system permission prompt that the Flutter test cannot tap, because it belongs to the operating system. Grant permissions before the run, for example with
adb shell pm grant <package> <permission>on Android, or use a build configuration that skips the prompt. - Keyboard and orientation. A software keyboard can cover the widget you want to tap. Scroll the widget into view first, and fix the orientation your tests expect.
- Animations disabled. On Android emulators, turning off system animation scales can make behaviour more consistent.
- Notifications and interruptions. On shared physical devices, incoming messages and update prompts can steal focus. Use devices dedicated to testing, in Do Not Disturb mode.
- Screen size. A layout can differ between a phone and a tablet. Pin the device used for the suite, or write assertions that hold at every size you support.
Scroll before you tap
A widget that is built but off-screen can be found, yet a tap on it misses. Use ensureVisible or scrollUntilVisible first:
final target = find.byKey(const Key('todo_item_42'));
await tester.scrollUntilVisible(
target,
200,
scrollable: find.byType(Scrollable).first,
);
await tester.tap(target);
await tester.pumpAndSettle();scrollUntilVisible scrolls by 200 logical pixels at a time until the finder matches a built widget. In a lazy list, items far down are not built until scrolled near, so a plain find returns nothing.
Diagnosing a flaky test
When a test fails only sometimes, do not guess. Follow a routine.
- Run the single test many times in a loop and count failures, so you know the failure rate.
- Read the first line of the error. "No matching nodes" points to timing or a missing key. A timeout points to
pumpAndSettleon a screen that never settles. - Run the test in isolation and then in the full suite. A difference points to leaked state.
- Compare a slow device or emulator with a fast one. A failure only on the slow one points to a missing wait.
- Print the widget tree with
debugDumpApp()at the point of failure to see what is on screen.
for i in $(seq 1 20); do
flutter test integration_test/app_test.dart -d <device_id> || echo "run $i failed"
doneFix the cause, then run the loop again. A test that passes twenty times in a row is much better evidence than one that passed once.
Checklist
- Every widget the test touches has a stable key.
- Waits are conditions (
pumpUntilFound) or bounded pumps, never fixed sleeps. pumpAndSettleis not used on screens with endless animation.- Network data, time, and randomness come from fakes or seeded sources.
setUpresets storage and singletons.- Permissions and device settings are prepared before the run.
- Off-screen widgets are scrolled into view before a tap.
Exercise
A test passes on your fast emulator but fails about one run in five on a slower physical phone with "Expected: exactly one matching node, Actual: no matching nodes" right after tapping a button that loads a list from a repository. The test uses await Future.delayed(const Duration(seconds: 1)) before the assertion. Name the cause and give two changes that fix it.
Show answer
The fixed one-second sleep is sometimes shorter than the load time on the slow phone, so the assertion runs before the list is built. Replace the sleep with a condition-based wait such as pumpUntilFound(tester, find.byKey(const Key('result_list'))), which polls until the widget appears or a timeout is reached. Also replace the live repository with a fake that returns seeded data, so load time no longer varies with the network or backend.
Exercise
A login test passes when run alone but fails when run after a test that logs in successfully. What is the likely cause, and how do you fix it?
Show answer
State from the earlier test, such as a stored session token or a logged-in user held in a singleton, leaks into the later test, so the app skips the login screen. Reset persisted storage and in-memory singletons in setUp (for example with SharedPreferences.setMockInitialValues({}) and a fresh app state), so each test starts from a known state.