Although the number of English-speaking or understanding people is growing day by day, there is a large number of people who can either speak or understand English. If you have a great use application people may not be able to use it. This is because people may not know English or prefer their local or mother tongue language. So you need to interchange app language in Flutter.

Your app may not be performing or giving value to non-English regions, no matter how much your app can bring great value and benefit to them. If you are developing a mobile application and you want to succeed at the international level, you must have to internationalize and localize your application.

Change app language in Flutter is like a piece of cake. In this tutorial, we’ll learn an easy way to implement Internationalization and Localization in the Flutter app by walking through some practical examples.

As of June 2023, this package supports 113 languages and language variants.

Demo App

change app language in Flutter

Here you are going learn to change languages English and Nepali.

All right now let’s dive to the code.

Step 1: Add dependencies

In this demo project, we are going to use some of the packages that are going to help us with flutter localization.

In the pubsec.yaml file add these dependencies.

dependencies:

  //other dependencies
  shared_preferences: ^2.2.0
  provider: ^6.0.5
  flutter_localization: ^0.1.14
  • shared_preferences: It is used to save the locale information of the application so that we can get the previously set language in the application.
  • provider: Provider is the state management, we are using in this project.
  • flutter_localization: Flutter localization assists us and making app localization in flutter. It assists us in switching app language in Flutter.

Step 2: Create JSON files for different languages

You need to have different JSON files. Inside it, we create an object for the items you want to switch app language in Flutter.

Create a directory in your root folder.

In the root folder create a directory named i18n. Inside create two files named en.json for English Language and ne.json for Nepali language.

en.json

{
    "localeDemo": "Localization Demo",
    "textToChange": "Text to Change"
}

ne.json

{
    "localeDemo": "स्थानीयकरण डेमो",
    "textToChange": "परिवर्तन गर्न पाठ"

}  
Keep in mind the keys need to be the same in both JSON files. You can keep adding different key values for the text you want to change.

Step 3: Create a provider file for state management

Inside the lib folder, create a file named app_langugage_provider.dart here we are going to change and hold the state of the language we selected.

class AppLanguageProvider extends ChangeNotifier {
   Locale _appLocale = const Locale("en");

  Locale get appLocal => _appLocale;
  fetchLocale() async {
    var prefs = await SharedPreferences.getInstance();
    if (prefs.getString('language_code') == null) {
      _appLocale = const Locale('en');
      return Null;
    }

    _appLocale = Locale(prefs.getString('language_code')!);
    notifyListeners();
    return Null;
  }

  void changeLanguage(Locale type) async {
    var prefs = await SharedPreferences.getInstance();
    if (_appLocale == type) {
      return;
    }
    if (type == const Locale("ne")) {
      _appLocale = const Locale("ne");
      await prefs.setString('language_code', 'ne');
      await prefs.setString('countryCode', 'NE');
    } else {
      _appLocale = const Locale("en");
      await prefs.setString('language_code', 'en');
      await prefs.setString('countryCode', 'US');
    }
    notifyListeners();
  }
}

Here we have two methods:

fetchLocale() : To get the locale or language in the state.

changeLanguage(): To change and save the locale selected.

Step 4: App Localization

Like there are GlobalMaterialLocalizations, you need to have localizations specific to your application. It is one of the most important methods to translate. You can call this method within your UI to specify localized strings.

Inside the lib folder, create a file named app_localizations.dart. It is going to be the helper class for localization delegates.

app_localizations.dart

class AppLocalizations {
  final Locale locale;

  AppLocalizations(this.locale);

  // Helper method to keep the code in the widgets concise
  // Localizations are accessed using an InheritedWidget "of" syntax
  static AppLocalizations? of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  // Static member to have a simple access to the delegate from the MaterialApp
  static const LocalizationsDelegate<AppLocalizations> delegate =
  AppLocalizationsDelegate();

  Map<String, String> _localizedStrings={};

  Future<bool> load() async {
    // Load the language JSON file from the "lang" folder
    String jsonString =
    await rootBundle.loadString('i18n/${locale.languageCode}.json');
    Map<String, dynamic> jsonMap = json.decode(jsonString);

    _localizedStrings = jsonMap.map((key, value) {
      return MapEntry(key, value.toString());
    });

    return true;
  }

  // This method will be called from every widget which needs a localized text
  String? translate(String key) {
    return _localizedStrings[key];
  }
}

Step 5: Create Localization Delegate

Inside lib the folder, create a file named app_localizations_delegate.dart. It is the application’s localization delegate.

A LocalizationsDelegate is an object that knows what to do when it’s time to load a particular language.

app_localizations_delegate.dart

class AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizations> {
  // This delegate instance will never change (it doesn't even have fields!)
  // It can provide a constant constructor.
  const AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    // Include all of your supported language codes here
    return ['en', 'ne'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    // AppLocalizations class is where the JSON loading actually runs
    AppLocalizations localizations =  AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

  @override
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

Step 6: Configure main.dart

Import the flutter_localizations library and specify localizationsDelegates and supportedLocales for your MaterialApp or CupertinoApp.

ChangeNotifierProvider(
      create: (BuildContext context) =>appLanguage,
      child: Consumer<AppLanguageProvider>(builder: (context, model, child) {
        return MaterialApp(
          title: 'Localization Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const HomePage(),
          locale: model.appLocal,
          supportedLocales: const [
            Locale('en', 'US'),
            Locale('ne', 'NP'),
          ],
          localizationsDelegates: const [
            AppLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate
          ],
        );
      })

Also, do not forget to ensure widget initialization and fetch the saved language which is going to the app language

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  AppLanguageProvider appLanguage = AppLanguageProvider();
  await appLanguage.fetchLocale();
  runApp( MyApp(
    appLanguage: appLanguage,
  ));
}

Step 5: Use as per your need

Inside your application you can now access localized strings and can use them as follows:

AppLocalizations.of(context)!.translate('localeDemo')!,

Step 6: Change app language in Flutter

You can change the app language when clicking the pop-up menu button as follows:

   PopupMenuButton<int>(
            color: Colors.white,
            itemBuilder: (context) => [
              // PopupMenuItem 1
              const PopupMenuItem(
                value: 1,
                // row with 2 children
                child: Row(
                  children: <Widget>[
                    Icon(Icons.abc,),
                    SizedBox(
                      width: 10,
                    ),
                    Text("English")
                  ],
                ),
              ),
              // PopupMenuItem 2
              const PopupMenuItem(
                value: 2,
                // row with two children
                child: Row(
                  children: [
                    Icon(Icons.nearby_off),
                    SizedBox(
                      width: 10,
                    ),
                    Text("Nepali")
                  ],
                ),
              ),
            ],
            elevation: 2,
            onSelected: (value) {
              if (value == 1) {
                appLanguage.changeLanguage(const Locale("en"));
              } else if (value == 2) {
                appLanguage.changeLanguage(const Locale("ne"));
              }
            },
          ),
      

Conclusion

Here you learned the importance of app localization in Flutter. Along with it, you learned the whole process of how you can switch app language in Flutter. You can now modify this code and make it useful for your needs. So play around with the code and do not forget to reach out in case of doubts.

Thanks for reading this article.

Also, follow to get updated on exciting articles and projects.

If I got something wrong? Let me know in the comments. I would love to improve.

Full Code:

https://github.com/nbnD/localization

_demo

Let’s get connected

We can be friends. Find on FacebookLinkedinGithubYouTube

BuyMeACoffee, and Instagram.

Contribute: BuyMeACoffee

ContactContact Us

  1. zoritoler imol Avatar

    Its good as your other blog posts : D, thanks for putting up. “What makes something special is not just what you have to gain, but what you feel there is to lose.” by Andre Agassi.

Leave a Reply

Your email address will not be published. Required fields are marked *

change app language in Flutter

Related Post