Sub topic 6
Connecting localizations to MaterialApp
This chapter assumes you can build a Flutter app with MaterialApp, and that you have already run flutter gen-l10n. You should have lib/l10n/app_localizations.dart and your ARB files in place. The generated class exists at this point, but nothing in the widget tree can reach it yet. Wiring connects the two.
What wiring does
Flutter does not load translations by itself. It uses a Localizations widget that sits in the tree and holds a set of loaded resources for one Locale. Widgets below it ask for a resource by type, for example AppLocalizations.
MaterialApp creates that Localizations widget for you. It needs two inputs:
localizationsDelegates: objects that know how to load a resource for a locale.supportedLocales: the locales your app can display.
Delegates
A delegate is a LocalizationsDelegate<T>. It has three jobs:
isSupported(locale)says whether it can serve a locale.load(locale)returns aFuture<T>with the resource.shouldReloadsays whether to reload when the delegate itself is replaced.
Loading is asynchronous. For the first frame, Localizations shows nothing until all delegates finish. Generated code returns an already completed future (SynchronousFuture), so in practice the first frame is not delayed.
Flutter's own widgets need strings too, such as the "OK" and "Cancel" buttons, date picker labels, and the tooltip on a back button. These come from separate delegates in flutter_localizations. Without them, the app throws an error when a widget asks for MaterialLocalizations in an unsupported locale.
The generated list
You do not need to assemble delegates by hand. The generated class exposes two static members:
AppLocalizations.localizationsDelegatesis a list holding the app delegate plusGlobalMaterialLocalizations.delegate,GlobalCupertinoLocalizations.delegate, andGlobalWidgetsLocalizations.delegate.AppLocalizations.supportedLocalesis a list built from the ARB files you have. Withapp_en.arbandapp_es.arb, it is[Locale('en'), Locale('es')].
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
home: const TripScreen(),
);
}
}The import path depends on synthetic-package. With synthetic-package: false, as in our l10n.yaml, the file sits in lib/l10n/ and you import it with a relative or package:your_app/l10n/app_localizations.dart path. With the older synthetic package default, the import was package:flutter_gen/gen_l10n/app_localizations.dart. Newer Flutter versions deprecate that route, so keep the explicit output.
Why `onGenerateTitle` and not `title`
The title property of MaterialApp is a plain String. It is read before any Localizations widget exists, so it cannot use a translation. onGenerateTitle is a callback that runs below Localizations. Its context can find AppLocalizations. The result appears in the task switcher on Android and in the web tab title.
Reading the resource
Once wired, any widget under MaterialApp can call AppLocalizations.of(context). The method looks up the nearest Localizations widget and returns the loaded instance.
The return type is nullable, AppLocalizations?. The generated code shows this because a lookup can fail if the delegate is missing. That is why the examples use !. If you want to avoid the bang everywhere, set nullable-getter: false in l10n.yaml. Then of(context) returns a non-null type. The failure then becomes an assertion at lookup time.
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: false
nullable-getter: falseMany teams wrap the lookup in an extension so that screens read context.l10n.appTitle:
import 'package:flutter/widgets.dart';
import 'l10n/app_localizations.dart';
extension AppLocalizationsX on BuildContext {
AppLocalizations get l10n => AppLocalizations.of(this)!;
}This is a convenience and not required. If you adopt it, use it consistently.
The context rule
The most common wiring error is calling AppLocalizations.of(context) with a context that sits above MaterialApp. Consider this code:
class BrokenApp extends StatelessWidget {
const BrokenApp({super.key});
@override
Widget build(BuildContext context) {
// This context belongs to BrokenApp, which is above MaterialApp.
final title = AppLocalizations.of(context)!.appTitle;
return MaterialApp(
title: title,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const TripScreen(),
);
}
}The context passed to build is the context of BrokenApp. No Localizations widget is above it, so of returns null, and the ! throws a null check error. The fix is to read the resource from a context created by MaterialApp: use onGenerateTitle, or put the code in a child widget or a Builder.
The same rule applies to dialogs and bottom sheets. They are built under the app's Navigator, which is under MaterialApp, so they find the resource. If you use a Builder inside home, the new context is below Localizations and also works.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Null check operator used on a null value` at `AppLocalizations.of(context)!` | The context is above `MaterialApp`, or delegates were not passed | Move the lookup below `MaterialApp`; pass `localizationsDelegates` |
| `No MaterialLocalizations found` | `GlobalMaterialLocalizations.delegate` is missing, for example after passing a custom delegate list | Include the Material delegate or use the generated list |
| `Target of URI doesn't exist` for `app_localizations.dart` | Code was not generated, or `generate: true` is missing, or the import path does not match `synthetic-package` | Run `flutter pub get` or `flutter gen-l10n`; check the import |
| App shows English only on a Spanish device | Locale is not in `supportedLocales` or the ARB file is not named correctly | Check the `@@locale` value and file name; see the next chapters on resolution |
| Task switcher title does not change | `title:` is used rather than `onGenerateTitle:` | Switch to `onGenerateTitle` |
Adding your own delegates
If you need extra delegates, such as one for a third-party package, combine them with the generated list instead of replacing it:
MaterialApp(
localizationsDelegates: [
...AppLocalizations.localizationsDelegates,
// Add extra delegates here.
],
supportedLocales: AppLocalizations.supportedLocales,
home: const TripScreen(),
)Replacing the list with only your own delegate is the usual cause of the MaterialLocalizations error in the table above.
Other app widgets
CupertinoApp and WidgetsApp take the same two properties. With WidgetsApp, you must supply a color and a pageRouteBuilder or routes. The delegates list still works because the generated list includes the widgets delegate.
If you use MaterialApp.router, pass the same properties to that constructor. The context rule still holds: translated text must come from widgets built by the router below MaterialApp.
Checking that wiring works
A fast check is a small screen that prints the resolved locale and one message:
class TripScreen extends StatelessWidget {
const TripScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final locale = Localizations.localeOf(context);
return Scaffold(
appBar: AppBar(title: Text(l10n.appTitle)),
body: Center(child: Text('${locale.toLanguageTag()}: ${l10n.greeting('Ada')}')),
);
}
}Change the device or emulator language and hot restart. Hot reload does not always re-run the locale resolution, so use a restart or a full relaunch. If the language tag changes but the text does not, the ARB file for that locale is missing or has not been generated.
Exercise
A teammate writes AppLocalizations.of(context)!.appTitle inside the build method of the widget that returns MaterialApp, and the app crashes with a null check error. Explain why, and give two ways to fix it.
Show answer
The context in that build method belongs to a widget above MaterialApp, so there is no Localizations widget above it and of returns null. Fix 1: use onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle, where the context is created below MaterialApp. Fix 2: move the lookup into a child widget such as TripScreen, or wrap it in a Builder placed inside home.
Exercise
You pass localizationsDelegates: [AppLocalizations.delegate] to MaterialApp, and a date picker throws "No MaterialLocalizations found". What is missing, and what is the simplest correction?
Show answer
The list lacks the Material, Cupertino, and widgets delegates from flutter_localizations. The simplest correction is to pass AppLocalizations.localizationsDelegates, or to spread it into your own list with ...AppLocalizations.localizationsDelegates and add any extra delegates after it.