Runtime language change in Flutter: solved exercise

Runtime language change in Flutter: solved exercise

Changing the language at runtime requires three pieces: a ChangeNotifier that stores the active Locale, passing that Locale to MaterialApp, and persisting it in SharedPreferences so it survives app restarts.

Problem statement

Implement a runtime language switcher that:

  • Allows switching between Spanish and English from the UI without restarting the app.
  • Persists the language preference in SharedPreferences.
  • Retrieves the saved language on app startup.
  • Uses Provider + ChangeNotifier to propagate the locale.
  • Dynamically updates MaterialApp.locale.

Dependencies

This exercise builds on the previous one (ARB + flutter_localizations).

1
2
3
4
5
6
7
8
9
dependencies:
  flutter_localizations:
    sdk: flutter
  intl: ^0.19.0
  provider: ^6.1.2
  shared_preferences: ^2.3.3

flutter:
  generate: true

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

// ── Locale manager ─────────────────────────────────────────────────────────────
class LocaleNotifier extends ChangeNotifier {
  static const _prefKey = 'app_locale';
  static const _supportedLocales = [Locale('en'), Locale('es')];

  Locale _locale = const Locale('en');

  Locale get locale => _locale;
  List<Locale> get supportedLocales => _supportedLocales;

  Future<void> load() async {
    final prefs = await SharedPreferences.getInstance();
    final code = prefs.getString(_prefKey);
    if (code != null) {
      final saved = _supportedLocales.firstWhere(
        (l) => l.languageCode == code,
        orElse: () => const Locale('en'),
      );
      _locale = saved;
      notifyListeners();
    }
  }

  Future<void> setLocale(Locale locale) async {
    if (locale == _locale) return;
    _locale = locale;
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefKey, locale.languageCode);
  }
}

// ── App entry point ────────────────────────────────────────────────────────────
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final localeNotifier = LocaleNotifier();
  await localeNotifier.load();
  runApp(
    ChangeNotifierProvider.value(
      value: localeNotifier,
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final localeNotifier = context.watch<LocaleNotifier>();
    return MaterialApp(
      title: 'Flutter i18n Runtime',
      locale: localeNotifier.locale,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: localeNotifier.supportedLocales,
      home: const HomeScreen(),
    );
  }
}

// ── Home screen ────────────────────────────────────────────────────────────────
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final localeNotifier = context.watch<LocaleNotifier>();
    final currentLocale = localeNotifier.locale;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.appTitle),
        actions: [_LanguageButton(current: currentLocale)],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(l10n.welcomeMessage, style: Theme.of(context).textTheme.titleMedium),
                    const SizedBox(height: 8),
                    Text(l10n.greeting('Flutter'), style: Theme.of(context).textTheme.bodyLarge),
                    const SizedBox(height: 4),
                    Text(l10n.currentDate(DateTime.now()), style: const TextStyle(color: Colors.grey)),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 24),

            Text(l10n.languageLabel, style: Theme.of(context).textTheme.titleSmall),
            const SizedBox(height: 8),

            ...localeNotifier.supportedLocales.map((locale) {
              final isSelected = locale == currentLocale;
              return Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: ListTile(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                    side: BorderSide(
                      color: isSelected
                          ? Theme.of(context).colorScheme.primary
                          : Colors.grey.shade300,
                      width: isSelected ? 2 : 1,
                    ),
                  ),
                  leading: Text(_flag(locale), style: const TextStyle(fontSize: 28)),
                  title: Text(_name(locale)),
                  subtitle: Text(locale.toLanguageTag()),
                  trailing: isSelected
                      ? Icon(Icons.check_circle, color: Theme.of(context).colorScheme.primary)
                      : null,
                  onTap: () => localeNotifier.setLocale(locale),
                ),
              );
            }),

            const Spacer(),
            _ActiveLocaleCard(locale: currentLocale),
          ],
        ),
      ),
    );
  }

  String _flag(Locale l) => switch (l.languageCode) {
        'es' => 'πŸ‡ͺπŸ‡Έ',
        'en' => 'πŸ‡¬πŸ‡§',
        _ => '🌐',
      };

  String _name(Locale l) => switch (l.languageCode) {
        'es' => 'EspaΓ±ol',
        'en' => 'English',
        _ => l.toLanguageTag(),
      };
}

class _LanguageButton extends StatelessWidget {
  final Locale current;
  const _LanguageButton({required this.current});

  @override
  Widget build(BuildContext context) {
    final localeNotifier = context.read<LocaleNotifier>();
    return PopupMenuButton<Locale>(
      icon: Text(_flag(current), style: const TextStyle(fontSize: 20)),
      tooltip: 'Change language',
      onSelected: (locale) => localeNotifier.setLocale(locale),
      itemBuilder: (context) => localeNotifier.supportedLocales
          .map((l) => PopupMenuItem(
                value: l,
                child: Row(
                  children: [
                    Text(_flag(l), style: const TextStyle(fontSize: 20)),
                    const SizedBox(width: 8),
                    Text(_name(l)),
                    if (l == current) ...[const Spacer(), const Icon(Icons.check, size: 16)],
                  ],
                ),
              ))
          .toList(),
    );
  }

  String _flag(Locale l) => switch (l.languageCode) {
        'es' => 'πŸ‡ͺπŸ‡Έ',
        'en' => 'πŸ‡¬πŸ‡§',
        _ => '🌐',
      };

  String _name(Locale l) => switch (l.languageCode) {
        'es' => 'EspaΓ±ol',
        'en' => 'English',
        _ => l.toLanguageTag(),
      };
}

class _ActiveLocaleCard extends StatelessWidget {
  final Locale locale;
  const _ActiveLocaleCard({required this.locale});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.green.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.green.shade200),
      ),
      child: Row(
        children: [
          const Icon(Icons.check_circle, color: Colors.green),
          const SizedBox(width: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Active locale: ${locale.toLanguageTag()}',
                  style: const TextStyle(fontWeight: FontWeight.bold)),
              const Text(
                'Saved in SharedPreferences β€” survives restart',
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Locale change flow

1
2
3
4
5
6
7
User selects language
  β†’ LocaleNotifier.setLocale(locale)
    β†’ _locale = locale; notifyListeners()
    β†’ SharedPreferences.setString('app_locale', 'en')
  β†’ MyApp rebuilds (context.watch)
    β†’ MaterialApp.locale = new locale
      β†’ Flutter rebuilds the tree with the new AppLocalizations

Common mistakes

  • Not calling load() before runApp: if you initialize LocaleNotifier but don’t await load(), the app always starts with the default locale until the first frame, causing a visible flash.
  • Using context.read inside build: context.read<LocaleNotifier>() does not subscribe the widget to changes. Inside build always use context.watch<LocaleNotifier>(). Use read only in callbacks (onTap, onPressed).
  • Forgetting that PopupMenuButton.onSelected should use context.read: in callbacks, context.watch would throw an exception because the context is no longer mounted when the callback runs. Use context.read in async callbacks.

Practical use

Runtime language switching is especially important in: language learning apps, tools for international teams, and any app where the user’s preferred language may differ from the operating system.

Guided practice and next step

FAQ

Can I use Riverpod or Bloc instead of Provider for the locale?

Yes. The pattern is the same: a StateNotifier/Cubit that stores the Locale and exposes it to MaterialApp. With Riverpod you would use a StateNotifierProvider<LocaleNotifier, Locale> and ref.watch in MyApp.

What happens if the user has an unsupported locale set (e.g., French)?

MaterialApp picks the best Locale from supportedLocales using Flutter’s locale resolution algorithm. If there is no exact language match, it uses the first element of supportedLocales. That’s why order matters: put the default language first.

How do I add region support (en-US vs en-GB)?

Add Locale('en', 'GB') to supportedLocales and create app_en_GB.arb with keys that differ from standard English. The remaining keys are inherited from app_en.arb automatically via the ARB fallback system.