Skip to content

2. Automatically saving & restoring the selected locale

Florin Bratan edited this page Nov 14, 2019 · 1 revision

Flutter Translate can automatically save the selected locale and restore it after application restart.

This can be done by passing an implementation of ITranslatePreferences during delegate creation:

 var delegate = await LocalizationDelegate.create(
      ...
        preferences: TranslatePreferences()
      ...

Example implementation using the shared_preferences package:

import 'dart:ui';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TranslatePreferences implements ITranslatePreferences
{
    static const String _selectedLocaleKey = 'selected_locale';

    @override
    Future<Locale> getPreferredLocale() async
    {
        final preferences = await SharedPreferences.getInstance();

        if(!preferences.containsKey(_selectedLocaleKey)) return null;

        var locale = preferences.getString(_selectedLocaleKey);

        return localeFromString(locale);
    }

    @override
    Future savePreferredLocale(Locale locale) async
    {
        final preferences = await SharedPreferences.getInstance();

        await preferences.setString(_selectedLocaleKey, localeToString(locale));
    }
}

And don't forget to reference the shared_preferences package in pubspec.yaml

dependencies:
  shared_preferences: <latest version>
Clone this wiki locally