Flutter Widget Test: solved UI testing exercise

Flutter Widget Test: solved exercise

If you are looking for Flutter widget test, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Problem statement

Build a screen with:

  • render a counter widget
  • tap button in test
  • assert updated UI state

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

class CounterWidget extends StatefulWidget {
  const CounterWidget({super.key});

  @override
  State<CounterWidget> createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            Text('$count'),
            ElevatedButton(onPressed: () => setState(() => count += 1), child: const Text('Add')),
          ],
        ),
      ),
    );
  }
}

void main() {
  testWidgets('increments counter when tapped', (tester) async {
    await tester.pumpWidget(const CounterWidget());

    expect(find.text('0'), findsOneWidget);
    await tester.tap(find.text('Add'));
    await tester.pump();
    expect(find.text('1'), findsOneWidget);
  });
}

Expected result

The test verifies interaction behavior and protects against future regressions.

Common mistakes

  • Forgetting pump after interactions.
  • Overfitting tests to fragile layout details.
  • Skipping critical user paths.

Practical use

Widget tests reduce UI regressions and speed up confident refactors.

Guided practice and next step

FAQ

What is the difference between unit and widget tests?

Unit tests validate isolated logic, widget tests validate rendered UI behavior.

Are widget tests enough?

Not always. Add integration tests for full multi-screen flows.

When should testing start?

As early as possible, especially for critical interactions.