Zuberu
Zuberu

Reputation: 101

How to change the Application's language programmatically in Flutter?

Currently, I am using flutter_localizations in order to translate strings in an application. It works perfectly fine, but it is required to be able to switch localization from the app's settings by pressing a button or choosing the language from a dropdown list. For this app, the BLoC design pattern is used.

Can you please suggest any potential solution to this problem? Thanks in advance :)

Upvotes: 10

Views: 9401

Answers (1)

Breno Teodoro
Breno Teodoro

Reputation: 483

For future readers, here's how you can achieve this:

The Locale is defined by the result returned from localeResolutionCallback function, within the MaterialApp widget.

In my case, I pass a final Locale defaultValue; to my app root, the first widget in the tree (declared in runApp()).

At that point, I simply do this validation:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'package:intl/intl.dart';

import '../../localization.dart';
import '../views/home_view.dart';

class App extends StatelessWidget {
  App({Key key, this.defaultLanguage}) : super(key: key);
  final Locale defaultLanguage;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeView(),
      localizationsDelegates: [
        AppLocalization.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', null),
        const Locale('pl', null),
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        if (defaultLanguage != null) {
          Intl.defaultLocale = defaultLanguage.toLanguageTag();
          return defaultLanguage;
        }
        if (locale == null) {
          Intl.defaultLocale = supportedLocales.first.toLanguageTag();
          return supportedLocales.first;
        }
        for (var supportedLocale in supportedLocales) {
          if (supportedLocale.languageCode == locale.languageCode) {
            Intl.defaultLocale = supportedLocale.toLanguageTag();
            return supportedLocale;
          }
        }
        Intl.defaultLocale = supportedLocales.first.toLanguageTag();
        return supportedLocales.first;
      },
    );
  }
}

If defaultLanguage was passed on by the bloc above, then it's used in the application, otherwise it does the standard validation to fetch the locale from the device.

Bear in mind that you might need to protect the check by verifying if the defaultLanguage variable is of a supported locale. In my case this is handled, so that's why I don't bother.

Upvotes: 8

Related Questions