riverpod localization
a demonstration of using riverpod for dynamic locale switching in-app, with persistence.
how it works
- fallback locale: declared inside
locale_state.dart
, and set with the @default decorator. - default locale: at startup, gets the system’s platform.localename (via dart:io) and uses it to set the app’s locale.
- if the platform locale does not match a supported locale
- the first matching language code locale will be set.
- otherwise, the fallback locale will be used.
- if the platform locale does not match a supported locale
- supported locales: these are stored in a provider, accessible from anywhere. update this list to add more locales.
- current locale: accessible from a provider anywhere the ref object is available. watch this provider to rebuild whenever the locale changes. you can still use
localizations.localeof(context)
to get the locale.
locale changes
- initstate sets the initial locale from the platform.
- app starts up with fallback locale
- initstate immediately attempts to restore a locale from persistent storage to riverpod state.
- if there is no locale in storage, attempts to use the platform’s locale.
- the drop down button can be used to select a new locale.
- this updates state and saves the locale to persistent storage.
- the
materialapp()
is wrapped in a riverpodconsumerwidget
which will rebuild automatically anytime the watchedref.watch()
locale value changes. - all translated strings are rebuilt as part of this process.
platform locale
the platform.locale
property of dart:io
library only works on mobile. for web, we need to use dart:html
‘s window.navigator.language.
this is implemented with the platformlocale()
interface and conditional imports.
dependencies
- state management: riverpod
- immutable state: freezed
- notice the custom converter used for saving
locale
tojson and fromjson. freezed works with json_serializable naturally.
- notice the custom converter used for saving
- internationalization / localization: flutter_localizations
- persistence: shared_preferences
getting started
code generator: this app uses build_runner to generate code for freezed.
# flutter pub run build_runner build --delete-conflicting-outputs
Comments are closed.