· 6 min read
Flutter Golden Tests: Catch Broken Share Cards Early
How to use Flutter golden tests to catch layout breaks in generated share images, with fixed sizes, real fonts, a small tolerance and CI diffs.
Flutter golden tests are the cheapest way I know to catch a broken image before a user shares it. In Mapika, my travel map app, people can turn their map into a shareable card. That card is a picture. If a long country name pushes a number off the edge, no unit test fails and no end-to-end test notices. The card still renders, it just looks wrong, and it looks wrong on someone else's feed. A golden test compares the rendered widget with a saved reference image, pixel by pixel, and fails when they differ.
This post shows how to set up golden tests for generated images like share cards: what to pin down, how to load real fonts, how to stop macOS and Linux from disagreeing, and how to read the failure in CI.
Why share cards need Flutter golden tests
Most tests check behavior. A Cubit emits the right state. A Maestro flow taps through onboarding and sees the right screen. I wrote about that in Maestro smoke tests in GitHub Actions. Those tests answer "does it work?"
A share card has a different failure mode. It always "works". The bugs are visual:
- A long place name wraps and overlaps the stats row.
- A theme change makes text the same color as the background.
- A padding refactor in a shared widget shifts the logo.
- A Flutter upgrade changes text layout slightly.
You only see these by looking. A golden test does the looking for you. It renders the widget in the test environment, saves a PNG the first time, and compares against that PNG on every run after.
A first golden test with a fixed size
The basic call is matchesGoldenFile. The Flutter API docs describe it: you pass a finder and a file name, and the test compares the widget's pixels with that file.
The key is to remove everything that changes between runs. For a share card that means a fixed canvas size, fixed data and no animation still running:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('share card, long place name', (tester) async {
tester.view.physicalSize = const Size(1080, 1350);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.light(),
home: RepaintBoundary(
child: ShareCard(data: ShareCardData.fixture(
title: 'Bosnia and Herzegovina',
visitedCount: 12,
badge: 'Explorer',
)),
),
),
);
await tester.pumpAndSettle();
await expectLater(
find.byType(ShareCard),
matchesGoldenFile('share_card_long_name.png'),
);
});
}
ShareCard, ShareCardData and AppTheme stand in for your own classes. A few details matter here:
- Set the view size in pixels.
tester.view.physicalSizewith a pixel ratio of 1 gives you an image the size of the real export. The card gets the same constraints it gets in production. - Use fixture data, not "now". A date or a counter that comes from the clock makes a new image on every run.
- Wrap the card in a
RepaintBoundary. The golden is taken from the nearest repaint boundary, so this keeps the image to the card only. - Settle first.
pumpAndSettlewaits for entry animations to finish. If the card has an endless animation, render a static variant for the test instead.
Keep golden tests in their own folder, such as test/goldens/. The PNGs are saved next to the test file. Create the reference images with:
flutter test --update-goldens test/goldens/
Open the PNGs and look at them before you commit. A golden is only as good as the image you approved. If the first image is already broken, the test will happily protect the broken version.
One golden per risky case
Do not try to cover everything. Pick the inputs that break layouts:
- the shortest and the longest names you expect,
- the largest numbers you show,
- light and dark theme,
- right-to-left text, if your app supports an RTL language.
Each case is one small test and one PNG. They are cheap to keep.
Load real fonts, or the golden is useless
If you skip this step, your first golden will be full of black rectangles. That is expected. By default, flutter_test renders text with a test font that draws every glyph as a box, so goldens do not depend on fonts installed on the machine.
Boxes are fine for checking layout, but a share card is about how it looks. You want to see the real typeface. You can load fonts from your assets before the tests run, with FontLoader:
// test/flutter_test_config.dart
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
TestWidgetsFlutterBinding.ensureInitialized();
final loader = FontLoader('Inter')
..addFont(rootBundle.load('assets/fonts/Inter-Regular.ttf'))
..addFont(rootBundle.load('assets/fonts/Inter-Bold.ttf'));
await loader.load();
await testMain();
}
Flutter picks up flutter_test_config.dart automatically for every test in that folder and below. The family name you pass to FontLoader must match the fontFamily in your theme. Use your own font files here: the point is that the font comes from the repo, not from the machine.
Images work the same way. An asset image may not be decoded by the time the golden is taken, so precache it inside tester.runAsync before you pump the card.
macOS and Linux will not agree
This is the classic golden test trap. You generate goldens on a Mac and push. CI on Linux fails on every golden, with differences you cannot see by eye. Text antialiasing is slightly different between platforms, so a few edge pixels change.
There are two fixes, and they work best together.
Pick one platform as the source of truth. CI on Linux is the natural choice, because that is where the check has to pass. You can still run the goldens locally to look at a diff, but the committed PNGs come from Linux. A small manual workflow in GitHub Actions that runs flutter test --update-goldens and uploads the PNGs as an artifact is enough.
Allow a tiny tolerance. The default comparator wants an exact match. You can replace it with one that accepts a very small difference:
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
class TolerantComparator extends LocalFileComparator {
TolerantComparator(super.testFile, {this.tolerance = 0.001});
final double tolerance; // 0.001 = 0.1% of pixels
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
final result = await GoldenFileComparator.compareLists(
imageBytes,
await getGoldenBytes(golden),
);
if (result.passed || result.diffPercent <= tolerance) {
result.dispose();
return true;
}
final error = await generateFailureOutput(result, golden, basedir);
result.dispose();
throw FlutterError(error);
}
}
Install it in the same flutter_test_config.dart, before testMain(). Reusing the default comparator's folder keeps each PNG next to its test:
final base = (goldenFileComparator as LocalFileComparator).basedir;
goldenFileComparator = TolerantComparator(base.resolve('golden_test.dart'));
Keep the tolerance small. A tenth of a percent hides antialiasing noise. A few percent hides real bugs, like a badge that moved. If you need a large tolerance to get green, the platforms are too different, and the first fix matters more.
Read the diff in CI
A failing golden in a CI log says only that the images differ. You need to see how. When a comparison fails, flutter_test writes a failures folder next to the test, with the reference image, the new image and two diff images that highlight the changed pixels.
Upload that folder when the job fails:
- name: Golden tests
run: flutter test test/goldens/
- name: Upload golden diffs
if: failure()
uses: actions/upload-artifact@v4
with:
name: golden-failures
path: test/goldens/failures/
Now a red check comes with pictures. Open the diff, and you know in seconds whether the change was intended. If it was, regenerate the goldens and commit the new PNGs in the same pull request. The reviewer then sees the image change next to the code change, which is a nice side effect: design changes get reviewed as images, not just as padding values.
Add failures/ to .gitignore so nobody commits the diffs by accident.
Takeaways
- Flutter golden tests catch the visual bugs that behavior tests miss, and generated images like share cards are the best place to start.
- Pin everything down: fixed view size, pixel ratio 1, fixture data, settled animations.
- Load real fonts with
FontLoaderinflutter_test_config.dart, or your goldens show boxes instead of text. - Generate goldens on one platform (CI) and allow only a tiny tolerance for antialiasing noise.
- Upload the
failuresfolder as a CI artifact, so every red golden comes with a visual diff.