Sub topic 14
Testing widgets under a specific locale
Localized text is easy to break without noticing. A renamed key, a plural branch missing from one language, or a wrong fallback all compile fine, and the app still runs. This chapter shows how to write widget tests that pin the locale, so the translated output is checked on every test run.
This chapter assumes you have the AppLocalizations class generated by gen-l10n and wired into MaterialApp, as in the earlier chapters. You should also know testWidgets, pumpWidget, and find from flutter_test. The examples use the Trip Planner app: the en template, an es translation, and the keys appTitle, greeting, tripCount, and departure. The package name is assumed to be trip_planner.
What a locale test needs
A test that reads AppLocalizations.of(context) needs the same three things as the real app:
- A
MaterialApp(orWidgetsApp) above the widget under test. localizationsDelegatesandsupportedLocalescopied from the generated class.- A way to choose the locale: either the
localeproperty, or a fake device locale.
Without the delegates, AppLocalizations.of(context) returns null, and the ! in your widget throws a null check error. Without a chosen locale, the test uses the test platform's default, which is normally en_US. In that case a test of the Spanish text fails, or worse, passes only on a developer's machine.
A single-locale test
The basic test forces a locale with the locale property of MaterialApp:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:trip_planner/l10n/app_localizations.dart';
void main() {
testWidgets('shows the Spanish plural for one trip', (tester) async {
await tester.pumpWidget(
MaterialApp(
locale: const Locale('es'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) =>
Text(AppLocalizations.of(context)!.tripCount(1)),
),
),
);
await tester.pumpAndSettle();
expect(find.text('1 viaje'), findsOneWidget);
});
}Two details matter here.
Buildersupplies the context. Thecontextof the test body sits above theMaterialApp, so it cannot see the localizations.Buildergives you a context that is belowMaterialApp.pumpAndSettlewaits for loading. Delegates load their messages through aFuture. The generated delegate usually completes it synchronously, but the Material and Cupertino delegates and the date formatting setup can take extra frames. Pumping until the tree settles removes any dependency on that timing.
A reusable helper
Repeating the delegate wiring in every test is noisy and easy to get wrong. Put it in one helper:
Future<void> pumpLocalized(
WidgetTester tester,
Widget child, {
Locale? locale,
}) async {
await tester.pumpWidget(
MaterialApp(
locale: locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: child,
),
);
await tester.pumpAndSettle();
}Because locale is nullable, the same helper also covers tests that want the default platform locale. Tests can now pass a real screen, such as const TripScreen(), instead of a Builder with a single Text.
Testing every language with one loop
Every plural branch in every locale deserves a check. A list of cases and a loop keeps this short. Each loop iteration registers its own test, so a failure names the locale and the count.
void main() {
final cases = <({Locale locale, int count, String text})>[
(locale: const Locale('en'), count: 0, text: 'No trips'),
(locale: const Locale('en'), count: 1, text: '1 trip'),
(locale: const Locale('en'), count: 3, text: '3 trips'),
(locale: const Locale('es'), count: 0, text: 'Sin viajes'),
(locale: const Locale('es'), count: 1, text: '1 viaje'),
(locale: const Locale('es'), count: 3, text: '3 viajes'),
];
for (final c in cases) {
testWidgets('tripCount(${c.count}) in ${c.locale}', (tester) async {
await pumpLocalized(
tester,
Builder(
builder: (context) =>
Text(AppLocalizations.of(context)!.tripCount(c.count)),
),
locale: c.locale,
);
expect(find.text(c.text), findsOneWidget);
});
}
}The =0 and =1 branches are the ones most often forgotten in a new translation, so test them explicitly. A language with more plural categories, such as Arabic or Polish, needs a case for each category you wrote in the ARB message.
Dates and numbers: compute the expectation
Formatted values come from the intl locale data. A hard-coded string such as '14 mar 2026' can break when the intl package updates its data. Build the expected string with DateFormat and the same skeleton the ARB file declares (yMMMd):
import 'package:intl/intl.dart';
testWidgets('formats the departure date per locale', (tester) async {
final date = DateTime(2026, 3, 14);
await pumpLocalized(
tester,
Builder(
builder: (context) =>
Text(AppLocalizations.of(context)!.departure(date)),
),
locale: const Locale('es'),
);
final expected = 'Sale el ${DateFormat.yMMMd('es').format(date)}';
expect(find.text(expected), findsOneWidget);
});This test checks two things: that the Spanish sentence is wired to the date placeholder, and that the date is formatted for es rather than en. It does not check the exact month abbreviation, which belongs to intl.
Create DateFormat after the pump. By then the generated delegate has initialized the date symbols for the locale. Creating one before the pump can throw a LocaleDataException.
Testing fallback
The locale resolution chapter explained that an unsupported locale falls back to the first entry of supportedLocales. With no localeResolutionCallback, you can lock that behavior in with a test. The fallback also applies to the locale property, because MaterialApp resolves it against supportedLocales.
testWidgets('falls back to English for an unsupported locale', (tester) async {
await pumpLocalized(
tester,
Builder(
builder: (context) =>
Text(AppLocalizations.of(context)!.tripCount(1)),
),
locale: const Locale('fr'),
);
expect(find.text('1 trip'), findsOneWidget);
});If you later add fr to the project, this test fails. Update it to use a language you still do not support. If you set a custom localeResolutionCallback, test that callback in the same way.
Simulating the device language
Setting locale on MaterialApp bypasses the part of your app that reads the device language. To test the real resolution path, change the locale of the fake platform instead. The test binding exposes platformDispatcher with test values:
testWidgets('follows the device language', (tester) async {
tester.platformDispatcher.localesTestValue = const [Locale('es')];
addTearDown(tester.platformDispatcher.clearAllTestValues);
await tester.pumpWidget(const MyApp());
await tester.pumpAndSettle();
expect(find.text('Planificador de viajes'), findsOneWidget);
expect(find.text('¡Hola, Ada!'), findsOneWidget);
expect(find.text('3 viajes'), findsOneWidget);
});This test uses the real MyApp, so it also confirms that main.dart passes the generated delegates and locales. addTearDown resets the fake device settings so later tests do not inherit Spanish. The app title appears in the AppBar of TripScreen, so the test finds it as normal text.
Setting a list of locales mimics a user with several preferred languages. Put Locale('fr') first and Locale('es') second to check that resolution skips unsupported entries.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Null check operator used on a null value` at `AppLocalizations.of(context)!` | The test `MaterialApp` has no `localizationsDelegates`, or the context is from above the app. | Pass the generated delegates and use `Builder` or a real child widget. |
| Text found in English when you expected Spanish | `locale` was not set, or `es` is missing from `supportedLocales`. | Set `locale`, and check the `app_es.arb` file exists and was generated. |
| `expect` fails only for the first frame | The test did not wait for delegates to load. | Call `pumpAndSettle` after `pumpWidget`. |
| Spanish leaks into later tests | A platform test value was never reset. | Register `addTearDown(tester.platformDispatcher.clearAllTestValues)`. |
| A date test fails after upgrading `intl` | The expected string was typed by hand. | Build it with `DateFormat` and the same skeleton. |
| `AppLocalizations` has no member for a new key | Generated code is stale. | Run `flutter gen-l10n` or `flutter pub get`, then run the tests again. |
Exercise
Write a test that pumps TripScreen with the locale es and checks that the greeting shows ¡Hola, Ada!. Which helper and which two properties of the test app make AppLocalizations.of(context) non-null?
Show answer
Use pumpLocalized(tester, const TripScreen(), locale: const Locale('es')); and then expect(find.text('¡Hola, Ada!'), findsOneWidget);. The MaterialApp inside the helper needs localizationsDelegates: AppLocalizations.localizationsDelegates and supportedLocales: AppLocalizations.supportedLocales. TripScreen is below the MaterialApp, so its context can find the localizations.
Exercise
Your test sets locale: const Locale('pt'), but the project supports only en and es, and en is listed first. Which text will the test see for tripCount(1), and why? How would you test the same path using the device language instead of the locale property?
Show answer
It sees 1 trip. Locale resolution cannot match pt, so MaterialApp falls back to the first supported locale, en. To use the device language, set tester.platformDispatcher.localesTestValue = const [Locale('pt')];, register addTearDown(tester.platformDispatcher.clearAllTestValues), and pump an app that has no locale property set.