Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

riverpod localization

a demonstration of using riverpod for dynamic locale switching in-app, with persistence.

drawing

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.
  • 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 riverpod consumerwidget which will rebuild automatically anytime the watched ref.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

getting started

code generator: this app uses build_runner to generate code for freezed.

# flutter pub run build_runner build --delete-conflicting-outputs

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.