Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(),
      );
like image 582
NiklasUllmann Avatar asked Jun 07 '26 21:06

NiklasUllmann


1 Answers

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.)

like image 131
Mäddin Avatar answered Jun 10 '26 12:06

Mäddin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!