FlutterAdvanced 2 min read

Flutter widget tests: interact and assert the result

Pump a widget, perform a user action and verify visible behavior; reserve integration tests for meaningful complete flows.

On this page

A widget test exercises interface behavior in Flutter’s test environment. It can verify a validation message or state update without booting a full device application. An integration test covers the assembled flow in a more complete runtime.

Assert a useful outcome

The fragment belongs in a test file after importing your application’s IdeaCounter widget. It follows the behavior of the first-app example, not its private implementation fields.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

testWidgets('a tap adds an idea', (tester) async {
  await tester.pumpWidget(const MaterialApp(home: IdeaCounter()));
  expect(find.text('0 ideas'), findsOneWidget);
  await tester.tap(find.byIcon(Icons.add));
  await tester.pump();
  expect(find.text('1 ideas'), findsOneWidget);
});

Read the result

pump renders the frame required by this state change. pumpAndSettle can be useful for finite transitions, but a permanently active animation may never settle. Use finders that describe stable roles or content, not accidental tree positions.

Read arrange, act and assert separately

pumpWidget establishes the screen under test. The first expectation describes the initial visible state. The tap is the user action, and pump lets Flutter process the resulting frame. The final expectation checks the changed label rather than the private counter field.

If the action triggers animation or asynchronous work, wait for the relevant condition deliberately. An indefinitely repeating animation is not a reason to wait for every animation to settle. Keep the test synchronized with the behavior being verified.

Use the form example to test invalid and valid submissions, then reserve a device-level flow for boundaries that a widget test cannot realistically cover.

Practice and verification

Test the validated form with invalid then valid input. Add an integration test for one critical saved-data flow, including relaunch or persistence when that is part of the contract.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.