How to persist selected language in Flutter?

To permanently save the app settings in Flutter, you need to store them somewhere on the device or the server. The easiest way to achieve that is with the help of the shared_preferences package.

Below you can find an example that demonstrates how to do that.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();

  runApp(MyApp(prefs: prefs));
}

class MyApp extends StatelessWidget {
  final SharedPreferences _prefs;

  const MyApp({Key? key, required SharedPreferences prefs})
      : _prefs = prefs,
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => LocaleModel(_prefs),
      child: Consumer<LocaleModel>(
        builder: (context, localeModel, child) => MaterialApp(
          title: 'Your app title',
          localizationsDelegates: AppLocalizations.localizationsDelegates,
          supportedLocales: AppLocalizations.supportedLocales,
          locale: localeModel.locale,
          /* ... */
        ),
      ),
    );
  }
}

class LocaleModel extends ChangeNotifier {
  Locale? _locale;
  final SharedPreferences _prefs;

  LocaleModel(this._prefs) {
    var selectedLocale = _prefs.getString("selectedLocale");
    if (selectedLocale != null) {
      _locale = Locale(selectedLocale);
    }
  }

  Locale? get locale => _locale;

  void set(Locale locale) {
    _locale = locale;
    _prefs.setString('selectedLocale', locale.toString());

    notifyListeners();
  }
}

Note: For more details on how to localize Flutter apps, see the example on GitHub.

Flutter internationalization tutorial:

Copyrights 2024 © Localizely