
In this tutorial you will learn how to internationalize your application. This is necessary if you plan to make your application available in multiple countries. Unlike frameworks like native Android, Flutter has no clear path to localization. It gives you a lot of freedom, which can be good if you know what you’re doing, but also extremely confusing if you’re just starting out. In this tutorial you will learn how to easily localize your applications by using JSON files to store strings in multiple languages. To this end, we follow the following steps:
- Create a new Flutter application,
- Prepare the project,
- Update the pubspec.yaml file,
- Location of material attachment,
- Working with user-defined strings,
- Translate the user interface.
1. Create a new Flutter project
Let’s create a new Flutter application. If you don’t know how to create a project, you can read the Hello World App in Flutter tutorial. For this tutorial, we will use the initial application that Flutter creates by default.
2. Project preparation
Before you write Dart code to access JSON files with translated strings, you must first create files and update the pubspec.yaml file. We will create a new language folder in the root directory of the project. All language files are stored in this folder. We will create two files – en.json for English and es.json for Spanish.
These files contain only simple pairs of strings with a key value. Using JSON is advantageous because it is similar to XML, you can simply pass it to the translator without having to access your code.
Here’s the code for N.J:
{
first_string : Hello, world !,
second_string : I hope this guide helps you
}
Here’s the code for SJ:
{
first_string : Hola Mundo!
second_string: Espero que este tutorial te ayude.
}
3. Update pubspec.yaml
Localization requires a dependency that comes directly from the Flutter SDK. And since we just added a new JSON file language, you need to specify it as an asset to access it in the code.
Addictions: tremors
flutter_location :
sdk : flutter
Assets:
– Language/en.json
– Language/es.json
4. Equipment location appendix
Localization is configured in the MaterialApp widget, which is the root of the Flutter application. Here you determine which languages are supported and what happens if the current device language is not supported.
import package:flutter/material.dart ;
import package:flutter_localizations/flutter_localizations.dart ;
Import ‘app_localizations.dart’ ;
void main() => runApp(MyApp()) ;
MyApp class extends StatelessWidget {
@override
widget build(BuildContext context) {
returns MaterialApp(
title : Flutter demonstration, Theme
: ThemeData(
primarySwatch : Colors.blue,
),
SupportLocales : [
locale(‘en’, ‘US’),
locale(‘es’, ‘ES’),
],
location delegates :
AppLocalizations.delegate,
// Built-in locale for basic text for hardware widgets
GlobalMaterialLocalizations.delegate,
// Built-in locale for LTR/RTL text direction
GlobalWidgetsLocalizations.delegate,
],
// Returns the locale to be used by the application
localeResolutionCallback : (locale, supportedLocales) {
// Checks if the current locale is supported
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode &&
supportedLocale.countryCode == locale.countryCode) {
returns supportedLocale;
}
}
// If the device locale is not supported, use the first
// in the list (in this case, English).
returns supportedLocales.first;
},
home: MyHomePage(),);}
The only thing that might be difficult to understand in the above code is the list of localizationDelegates. LocalizationsDelegate is an object that knows what to do when it is time to load a particular language.
In addition to using AppLocalizations that you haven’t already created, you also specify some predefined locations for materials and widgets.
Many widgets in the content pack contain text. The Hardware Alert dialog box may be opened. For example, include a cancel button. This button is available by default, you don’t have to write the text yourself. Flutter has such default strings that are already localized, you just need to specify a delegate.
5. Working with user chains
Just as there are GlobalMaterialLocalizations, you also want to have application-specific localizations, hence the name of the AppLocalizations class. The most important method is the translate() method. You can then call the translate() method on the UI widgets to specify the localized strings.
Create a new app_localizations.dart file in the lib folder. First we create an AppLocalizations class that will have two methods – load() to load JSON into the<String, String> folder in memory and translate() to open the translated String folder.
Here is the code of the file:
import dart:async ; import
dart:convert ;
import ‘package:flutter/material.dart’ ; import
‘package:flutter/services.dart’ ;
class AppLocalizations {
end locale ;
Places (this.locale);
// Method to keep code compressed in widgets
// Access localizations using the InheritedWidget syntax
static AppLocalizations of(BuildContext context) {
return Localizations.of(context, AppLocalizations);
}
Map<String, String> _localizedStrings ;
Future load() async {
// Load the language JSON file from the language folder
String jsonString =
wait rootBundle.loadString(‘language/${local.languageCode}.json’);
Map<String, dynamic> jsonMap = json.decode(jsonString) ;
_localizedStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
}) ;
return true;
}
// This method is called by any widget that needs localized text
String translate(String key) {
return _localizedStrings[key];
}
}
The above class contains the actual logic. However, you still need to provide a way for Flutter to step in and decide when to call the load() method and which locale to use.
Delegates are used for this initialization in flutter localization. Create a new batch-private _AppLocalizationsDelegate class that extends LocalizationsDelegate. It’s personal because you don’t have to put it in another file.
To access this delegate, create a new static field in the AppLocalizations class:
import dart:async ; import
dart:convert ;
import ‘package:flutter/material.dart’ ; import
‘package:flutter/services.dart’ ;
AppLocalizations class {
…
// static member for easy access to MaterialApp delegation
static constants LocalizationsDelegate delegation =
_AppLocalizationsDelegate();
…
}
// LocalizationsDelegate is a factory for a set of localized resources
// In this case, the localized strings are obtained in the AppLocalizations
class _AppLocalizationsDelegate
extends LocalizationsDelegate {
// This instance of the delegate will never change (it doesn’t even have fields!)
// It can provide a constant constructor.
const _AppLocalizationsDelegate() ;
@override
bool isSupported(locale locale) {
// Include all supported language codes here
return [‘en’, ‘sk’].contains(locale.languageCode);
}
@override
Future load(Locale) async {
// The AppLocalizations class actually executes the JSON load
AppLocalizations localizations = new AppLocalizations(locale);
await localizations.load();
return localizations;
}
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}
6. Translate user interface
Once all these settings are in place, call the static helper method of() from AppLocalizations() to get the correctly configured instance of Flutter, then translate your content using the keys specified in the JSON files.
Here is the code for main.dart:
import package:flutter/material.dart ;
import package:flutter_localizations/flutter_localizations.dart ;
import app_localization.dart ;
void main() => runApp(MyApp()) ;
MyApp class extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title : ‘Flutter Demo’,
theme : ThemeData(
primarySwatch : Colors.blue,
),
// This list lists all languages supported by the application
supportedLocales : [
Locale(‘en’, ‘US’),
Locale(‘es’, ‘ES’),
],
// These delegates cause the localization data for the desired language to be loaded
localizationsDelegates: [
// These delegates are added later
// The class that loads translations from JSON files
AppLocalizations.delegates,
// Built-in localizations for the main text of hardware widgets
GlobalMaterialLocalizations.delegates,
// Built-in localizations for the direction of LTR/RTL text
GlobalWidgetsLocalizations.delegate,
],
// Returns the locale to be used by the application
localeResolutionCallback : (locale, supportedLocales) {
// Checks if the current locale is supported
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode &&
supportedLocale.countryCode == locale.countryCode) {
return supportedLocale;
}
}
// If the locale of the device is not supported, use the first
// in the list (English in this case).
return supportedLocales.first;
},
home : MyHomePage(),
);
}
}
MyHomePage class extends StatelessWidget {@overrideWidget build(BuildContext context) {returns body scaffold(body : Center(child : Padding(padding : const EdgeInsets.all(8.0), child : Column(mainAxisSize : MainAxisSize.min, children : [Text(AppLocalizations.of(context).translate(‘first_string’), style : TextStyle(fontSize: 25),textAlign : TextAlign.center,),SizeBox(height : 10),Text(AppLocalizations.of(context).translate(‘second_string’),style : TextStyle(fontSize: 25),textAlign : TextAlign.center,),SizeBox(height: 10),Text(‘This is not translated’,style : TextStyle(fontSize: 25),textAlign : TextAlign.center,), }
To check if this internationalization works on the device/emulator, try changing the language of the device in the settings.
Here’s the output:
And this is what happens after you change the settings:
I hope this lesson on Flutter has been helpful to you. If you want to learn more about Flutter, check out the other Flutter tutorials on this page. Some include video tutorials.
Have fun learning Flutter!
Related Tags:
flutter easy localization,flutter change language,flutter change locale programmatically,flutter localization arabic,flutter multi language example,flutter intl,Privacy settings,How Search works,flutter localization example github,flutter intl example