Sub topic 12
Letting users change the language at runtime
By default, a Flutter app follows the device language. Many apps also let users pick a language inside the app, for example to use Spanish on an English phone. This chapter shows how to add that choice, keep it across launches, and avoid the usual mistakes.
This chapter assumes you have finished the earlier chapters. You should have a working AppLocalizations class generated by gen-l10n and a MaterialApp wired with localizationsDelegates and supportedLocales. You should also be comfortable with ChangeNotifier and with async code in main.
How the locale reaches the widgets
MaterialApp has a locale property. The value decides which Locale the Localizations widget loads for everything below it.
- When
localeisnull, Flutter reads the device's preferred languages and picks the best match fromsupportedLocales. This is the behavior you have had so far. - When
localeis non-null, Flutter uses that locale and skips the device-language matching. The locale is then passed to each delegate.
If you change the property and rebuild MaterialApp, Localizations loads the new messages and rebuilds every widget that called AppLocalizations.of(context). The widget tree keeps its state, so a form half filled in does not reset. Text direction also follows the new locale, so switching to Arabic or Hebrew flips the layout without extra code.
Holding the chosen locale
The selected locale is app-wide state, so it must live above MaterialApp. A small ChangeNotifier is enough. A null locale means "follow the system", which gives the user a way back to the default.
This example stores the choice with the shared_preferences package. Add it with flutter pub add shared_preferences. Any storage works, as long as you can read it before the first frame.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'l10n/app_localizations.dart';
class LocaleController extends ChangeNotifier {
LocaleController(SharedPreferences prefs)
: _prefs = prefs,
_locale = _read(prefs);
static const _key = 'locale';
final SharedPreferences _prefs;
Locale? _locale;
/// null means "follow the device language".
Locale? get locale => _locale;
static Locale? _read(SharedPreferences prefs) {
final code = prefs.getString(_key);
if (code == null) return null;
final saved = Locale(code);
// A stored value can be stale, for example after a language is removed.
return AppLocalizations.supportedLocales.contains(saved) ? saved : null;
}
Future<void> setLocale(Locale? locale) async {
if (locale == _locale) return;
_locale = locale;
notifyListeners();
if (locale == null) {
await _prefs.remove(_key);
} else {
await _prefs.setString(_key, locale.languageCode);
}
}
}The controller notifies listeners before it writes to disk, so the UI responds at once. The check in _read matters. If a user saved de and a later release drops German, passing that locale to MaterialApp would make the generated delegate throw while loading. The contains check turns a stale value back into null.
Rebuilding MaterialApp when the locale changes
Read the saved choice before runApp, so the first frame already uses the right language. Without that, users would see a flash of the device language.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
runApp(MyApp(controller: LocaleController(prefs)));
}
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.controller});
final LocaleController controller;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
return MaterialApp(
locale: controller.locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
home: TripScreen(controller: controller),
);
},
);
}
}ListenableBuilder rebuilds only MaterialApp and below, which is the right scope. You can use Provider, Riverpod, or another state tool instead. What matters is that MaterialApp rebuilds with a new locale value.
Building the language picker
The picker needs a label for "follow the system", so add one message to both ARB files. Remember to run flutter gen-l10n or flutter pub get afterward.
{
"languageSystem": "System default",
"@languageSystem": {
"description": "Option in the language picker that follows the device language"
}
}In app_es.arb, add "languageSystem": "Predeterminado del sistema".
Language names do not belong in ARB files. Show each language in its own language ("Español", not "Spanish"). A user who accidentally switched to a language they cannot read can then still find their own.
const _languageNames = {
'en': 'English',
'es': 'Español',
};
class LanguagePicker extends StatelessWidget {
const LanguagePicker({super.key, required this.controller});
final LocaleController controller;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return DropdownButton<Locale?>(
value: controller.locale,
onChanged: controller.setLocale,
items: [
DropdownMenuItem<Locale?>(
value: null,
child: Text(l10n.languageSystem),
),
for (final locale in AppLocalizations.supportedLocales)
DropdownMenuItem<Locale?>(
value: locale,
child: Text(
_languageNames[locale.languageCode] ?? locale.toLanguageTag(),
),
),
],
);
}
}The picker builds its list from AppLocalizations.supportedLocales. Adding a new ARB file therefore adds a new menu entry, and you only need to add its name to _languageNames. Place the picker anywhere below MaterialApp, for example in the AppBar of TripScreen:
appBar: AppBar(
title: Text(l10n.appTitle),
actions: [LanguagePicker(controller: controller)],
),Reading the active locale
Sometimes you need to know which locale is in use, for example to format a value by hand or to log it. Use Localizations.localeOf(context). Do not read controller.locale for this. That value is null when the app follows the system, and it also says nothing about the locale Flutter picked after matching.
final active = Localizations.localeOf(context);
Text('Language code: ${active.languageCode}');The call registers a dependency, so the widget rebuilds when the locale changes.
Edge cases and common errors
- Passing an unsupported locale. A locale outside
supportedLocalesis not rescued by the fallback rules from the previous chapter. The generated delegate throws aFlutterErrorthat says the locale is not supported. Validate stored or server-provided values, as_readdoes above. - Creating the controller inside
build. IfMyApp.buildcreates a newLocaleController, every rebuild resets the choice. Create it once, inmainor in aStateobject. - Restoring the choice too late. If you load the saved value after the first frame, users see one frame in the wrong language. Load it before
runApp, or show a splash screen until it is ready. - Storing only the language code. The example saves
languageCode, which suits languages such asenandes. If you ship regional variants such aspt_BRandpt_PT, storetoLanguageTag()and restore it withLocale.fromSubtagsorLocale.forLanguageTag(available in newer Flutter versions). Otherwise the saved value will not match your supported list. - Translating language names. A dropdown that shows "Spanish" in English and "Español" in Spanish is harder to use than one that always shows "Español".
- Cached strings. If you store
l10n.appTitlein a field or in astaticvariable, it keeps the old language after a switch. CallAppLocalizations.of(context)inbuildeach time.
Testing the switch
You can test the whole flow without a device. Pump the app, change the controller, and check that the text changed. This test uses a fake in-memory store so nothing touches disk:
testWidgets('switching to Spanish updates the title', (tester) async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final controller = LocaleController(prefs);
await tester.pumpWidget(MyApp(controller: controller));
await tester.pumpAndSettle();
expect(find.text('Trip Planner'), findsOneWidget);
await controller.setLocale(const Locale('es'));
await tester.pumpAndSettle();
expect(find.text('Planificador de viajes'), findsOneWidget);
});The test assumes the default test locale is English, which holds in Flutter widget tests. To make that explicit, set controller.setLocale(const Locale('en')) first.
Exercise
A user selects Spanish, closes the app, and reopens it. The app starts in English for a moment and then switches to Spanish. What causes this, and how do you fix it?
Show answer
The saved locale is being read asynchronously after the first frame, so MaterialApp first builds with locale null (the device language) and then rebuilds when the value arrives. Read the stored value before calling runApp: make main async, call WidgetsFlutterBinding.ensureInitialized(), await SharedPreferences.getInstance(), and pass the controller, which reads the value synchronously in its constructor, into MyApp.
Exercise
Why does the picker offer a null option, and what does choosing it do?
Show answer
Null means "follow the device language". Passing null to MaterialApp.locale makes Flutter resolve the locale from the device's preferred languages and supportedLocales again. Without this option, once users pick a language they could never return to automatic behavior, and the controller removes the saved value so the next launch also follows the system.