NiklasUllmann
NiklasUllmann

Reputation: 77

Flutter change Localization programatically

I followed the new Flutter Tutorial (https://flutter.dev/docs/development/accessibility-and-localization/internationalization) for Localizations and it works like a charm.

But I have a question:

Is it possible to change the Locale when the user taps a button?

MaterialApp(
        debugShowCheckedModeBanner: false,
        localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
        title: "MyApp",
        theme: ct.theme,
        home: MyHomePage(),
      );

Upvotes: 3

Views: 1472

Answers (1)

Mäddin
Mäddin

Reputation: 1319

You can pass your wished locale to the MaterialApp. If it is null, the app will take the system language. In that way you can wrap your MaterialApp in an InheritedWidget for changing the locale from anywhere in the widget tree. It's not an elegant but a simple solution. My InheritedWidget looks like this:

class MyI18n extends InheritedWidget {
  final Function(Locale) _localeChangeCallback;

  const MyI18n(
      this._localeChangeCallback,{
    Key key,
    @required Widget child,
  })  : assert(child != null),
        super(key: key, child: child);

  static MyI18n of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyI18n>();
  }

  void changeLocale(Locale locale) {
    _localeChangeCallback?.call(locale);
  }

  @override
  bool updateShouldNotify(MyI18n old) {
    return true;
  }
}

You can also save the locale in the InheritedWidget for using it in updateShouldNotify :)

Your MaterialApp will look like this:

MyI18n(
  (locale) => setState(() => this._locale = locale),
  child: MaterialApp(locale: _locale, ...),
),

For using it: MyI18n.of(context).changeLocale(locale)

There are other ways for changing the locale but in my opinion this one is really simple. (You can do it the same way but with less code by using a Provider and/or a Bloc.)

Upvotes: 1

Related Questions