0
0
Fluttermobile~5 mins

Golden tests for UI in Flutter

Choose your learning style9 modes available
Introduction

Golden tests help you check if your app's screen looks right. They compare your UI to a saved picture to catch mistakes early.

When you want to make sure a button or screen looks the same after changes.
When you add new UI features and want to avoid breaking old designs.
When you fix bugs and want to confirm the UI stays correct.
When you want to test different screen sizes or themes visually.
When you want to automate UI checks in your app development.
Syntax
Flutter
testWidgets('description', (WidgetTester tester) async {
  await tester.pumpWidget(MyWidget());
  await expectLater(
    find.byType(MyWidget),
    matchesGoldenFile('goldens/my_widget.png'),
  );
});

testWidgets runs a UI test.

matchesGoldenFile compares the widget to a saved image file.

Examples
This test checks if the button looks like the saved image.
Flutter
testWidgets('Button looks correct', (tester) async {
  await tester.pumpWidget(MaterialApp(home: ElevatedButton(onPressed: () {}, child: Text('Tap'))));
  await expectLater(find.byType(ElevatedButton), matchesGoldenFile('goldens/button.png'));
});
This test compares the whole screen widget to the golden file.
Flutter
testWidgets('Screen matches golden', (tester) async {
  await tester.pumpWidget(MyScreen());
  await expectLater(find.byType(MyScreen), matchesGoldenFile('goldens/screen.png'));
});
Sample App

This test shows a simple text widget and compares it to a saved golden image named 'text_widget.png'.

Flutter
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('Simple Text widget golden test', (WidgetTester tester) async {
    await tester.pumpWidget(const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('Hello Golden Test'),
        ),
      ),
    ));

    await expectLater(
      find.byType(Text),
      matchesGoldenFile('goldens/text_widget.png'),
    );
  });
}
OutputSuccess
Important Notes

Golden files are images saved in your project to compare UI snapshots.

Run tests with flutter test and update golden files with flutter test --update-goldens if UI changes are intentional.

Keep golden files in a dedicated folder like goldens/ for organization.

Summary

Golden tests compare your UI to saved images to catch visual bugs.

They are useful for checking buttons, screens, and themes.

Use matchesGoldenFile inside testWidgets to write golden tests.