Sub topic 7
Using translated strings in widgets
This chapter covers how widgets read the messages that gen-l10n generated. It assumes you have already generated AppLocalizations, wired localizationsDelegates and supportedLocales into MaterialApp, and can write a StatelessWidget and a StatefulWidget. Placeholders, plurals and formatting get their own chapters. Here the focus is on how lookup works and where it goes wrong.
What AppLocalizations.of(context) does
AppLocalizations is an abstract class that gen-l10n creates from your template ARB file. The generator also creates one subclass per language, such as AppLocalizationsEn and AppLocalizationsEs. Each ARB key becomes a member of the abstract class:
- A message without placeholders becomes a getter, such as
l10n.appTitle. - A message with placeholders becomes a method, such as
l10n.greeting('Ada').
AppLocalizations.of(context) is a static method that calls Localizations.of for your type. Localizations is a widget that MaterialApp inserts into the tree. It holds the objects the delegates loaded for the current locale. The lookup walks up the tree from context, finds that widget, and returns the AppLocalizations instance for the active locale.
Two consequences follow from this design:
- The call registers a dependency on the
Localizationswidget. When the locale changes, Flutter rebuilds every widget that calledof(context), and the new text appears without extra code. - The lookup needs a
BuildContextthat sits belowMaterialApp. Without one, there is nothing to find.
The basic pattern
Read the object once at the top of build and reuse it. The generated getters are cheap, so the local variable is for readability.
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';
class TripScreen extends StatelessWidget {
const TripScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(title: Text(l10n.appTitle)),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(l10n.greeting('Ada')),
Text(l10n.tripCount(3)),
],
),
),
);
}
}Note that Text(l10n.appTitle) cannot be const, because the value depends on the locale at runtime. Remove const from any widget subtree that contains a translated string. The analyzer's prefer_const_constructors lint will not complain in these places, because the expression is not constant.
The null check
By default, of returns AppLocalizations?. That is why the examples use !. It returns null when no Localizations widget above the context holds your type. In a correctly wired app this does not happen below MaterialApp.
If the ! bothers you, add this line to l10n.yaml:
nullable-getter: falseAfter you run flutter gen-l10n (or flutter pub get with generate: true), of returns a non-nullable AppLocalizations. Code that writes ! still compiles, but the analyzer reports an unnecessary non-null assertion. Pick one style for the whole project.
A small extension for readability
Many teams add a one-line extension so that call sites read context.l10n.appTitle. This is optional and does not change behavior.
import 'package:flutter/widgets.dart';
import 'l10n/app_localizations.dart';
extension AppLocalizationsX on BuildContext {
AppLocalizations get l10n => AppLocalizations.of(this)!;
}The extension hides the !. If you later move the lookup somewhere that has no localizations, you get the same runtime error as before, just from one place.
Where you can and cannot look up messages
The lookup depends on the widget tree, so the place you call it matters.
| Location | Works? | Notes |
|---|---|---|
| `build` of any widget below `MaterialApp` | Yes | The normal case. |
| `didChangeDependencies` of a `State` | Yes | Runs again when the locale changes. |
| `initState` | No | Throws, because dependencies cannot be read before `initState` completes. |
| `build` of the widget that creates `MaterialApp` | No | That `context` is above `Localizations`. |
| Callbacks such as `onPressed` | Yes | Capture `context` from `build` and call `of` inside the callback. |
| Code with no `BuildContext` (repositories, services) | No | Return keys or data, and translate in the UI. |
Mistake: looking up above MaterialApp
This is the most common failure. The context passed to MyApp.build belongs to MyApp, which is above the MaterialApp it returns:
class BrokenApp extends StatelessWidget {
const BrokenApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
// Wrong: context is above MaterialApp, so of(context) returns null.
title: AppLocalizations.of(context)!.appTitle,
home: const TripScreen(),
);
}
}The ! throws a null check error at startup. The fix is onGenerateTitle, which MaterialApp calls with a context that is below its own Localizations:
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,The same applies to anything else you build in that method. If you need localized text beside MaterialApp itself, wrap the part that needs it in a Builder placed inside home, or move it into its own widget.
Mistake: calling of(context) in initState
class _SearchBoxState extends State<SearchBox> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
// Wrong: throws, because dependencies cannot be read in initState.
_controller = TextEditingController(
text: AppLocalizations.of(context)!.searchHint,
);
}
// ...
}Use didChangeDependencies for work that needs a translated value. Flutter calls it right after initState and again whenever an inherited dependency changes, so it also tracks locale switches. Guard any one-time work yourself, because the method runs more than once:
class SearchBox extends StatefulWidget {
const SearchBox({super.key});
@override
State<SearchBox> createState() => _SearchBoxState();
}
class _SearchBoxState extends State<SearchBox> {
String? _hint;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_hint = AppLocalizations.of(context)!.appTitle;
}
@override
Widget build(BuildContext context) {
return TextField(decoration: InputDecoration(hintText: _hint));
}
}For most cases you can skip the state field and read the message directly in build. Reach for didChangeDependencies only when you must compute something once per locale.
Strings outside the widget tree
A repository, a bloc or a notification handler has no BuildContext. Do not pass a context deep into business logic just to get text. Two approaches work well:
- Return data, such as an enum value, an error code or a number, and let the widget map it to a message.
- Resolve the message in the widget and hand the finished string to the other layer.
A mapping function in the UI layer keeps the logic testable:
enum TripError { notFound, offline }
String describeError(AppLocalizations l10n, TripError error) {
switch (error) {
case TripError.notFound:
return l10n.appTitle; // replace with a dedicated message key
case TripError.offline:
return l10n.greeting('offline'); // replace with a dedicated message key
}
}The two return lines use existing keys only so the example compiles with the ARB files from this tutorial. In a real app each case gets its own key. The point is the shape: the function takes AppLocalizations as a parameter, so a test can pass a specific language without any widgets.
If you must translate without a context, such as in a background notification, you can construct a specific language directly with AppLocalizationsEs(). Prefer this only when the language is known from stored user settings, because it bypasses locale resolution.
Does text flash in the wrong language at startup?
Delegates load asynchronously by contract. The generated delegate, however, returns a synchronous future for supported locales, so the translated text is available on the first frame. You do not need a loading state for AppLocalizations. Packages that load translations from the network or from disk are different, and the pattern above does not remove their loading time.
Checklist when a string does not translate
- Confirm the key exists in the template ARB file and that you re-ran generation after editing it.
- Confirm
supportedLocalesincludes the language. If it does not, Flutter falls back to another locale and you see the fallback text. - Confirm the call site is below
MaterialAppand not ininitState. - Confirm the text is not a hard-coded literal that was never moved into an ARB file.
Exercise
A teammate writes title: AppLocalizations.of(context)!.appTitle in the build method of the widget that returns MaterialApp. The app crashes at launch with a null check error. Why does it happen, and what is the fix?
Show answer
The context in that build method belongs to a widget above MaterialApp, so no Localizations widget is found and of returns null; the ! then throws. Use onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle, which receives a context below MaterialApp's Localizations.
Exercise
You need to set a TextField hint from a translated message once per language, and your first attempt in initState throws. Where should the lookup go, and why is it safe to run there more than once?
Show answer
Move it to didChangeDependencies (or read it directly in build). Flutter calls didChangeDependencies after initState and again whenever the locale changes, so the hint updates with the language. The assignment is idempotent, so repeated calls do no harm.