Localization is a critical aspect of app development that ensures your application can reach a global audience. By translating an app’s text and non-text elements into various languages, you enhance user experience and accessibility. This guide will walk you through the steps of integrating localization into your Flutter application, focusing on text elements. Whether you’re a seasoned developer or a newcomer, this step-by-step tutorial will help you master the process of localizing your Flutter app.
Why Localization Matters
In today’s global market, creating an app that supports multiple languages is crucial for maximizing user reach and engagement. Localization involves more than just translating text; it encompasses adapting various elements to cater to different cultural norms and preferences. By localizing your app, you not only make it accessible to non-English speaking users but also increase its chances of success in international markets.
Setting Up Localization in Flutter
Step 1: Managing Dependencies
To begin, you need to add the necessary dependencies to your pubspec.yaml
file. This file manages the packages your Flutter app requires. Add the following lines:
dependencies:
flutter_localizations:
sdk: flutter
intl: any
After updating the pubspec.yaml
file, run the following command in your terminal to download these dependencies:
flutter pub get
Step 2: Creating Files and Folders
To handle localizations, create the following folder structure within your lib/
directory:
lib/
|-- l10n/
|-- app_en.arb
|-- app_es.arb
|-- app_ar.arb
Each app_<language_code>.arb
file will contain translations for a specific language.
Example of ARB Files
‘app_en.arb'
:
{
"helloWorld": "Hello World!"
}
'app_es.arb'
:
{
"helloWorld": "¡Hola Mundo!"
}
‘app_ar.arb
‘:
{
"helloWorld": "مرحبا بالعالم!"
}
Step 3: Configuring Localization Tool
Create a new l10n.yaml
file in the root of your project. This file configures the gen_l10n
tool, which generates localization files. Here’s an example configuration:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
Step 4: Enabling Generation of Localization Files
To enable the automatic generation of localization files, update the flutter
section of the pubspec.yaml
file:
flutter:
generate: true
Step 5: Adding Translations
With the l10n.yaml
file configured and the necessary dependencies installed, add translations to your .arb
files. These files will contain key-value pairs for each piece of text you want to localize.
Step 6: Configuring Main Widgets
In your main.dart
file, import the necessary packages and configure the MaterialApp
widget to use the localization delegates:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MyHomePage(),
);
}
}
The AppLocalizations.localizationsDelegates
and AppLocalizations.supportedLocales
handle the localization process, allowing the app to display text in different languages based on the user’s preferences.
Step 7: Using Localized Text
To use localized text in your widgets, access the keys from the .arb
files using the AppLocalizations
class:
Text(AppLocalizations.of(context)!.helloWorld)
If everything is set up correctly, running your app should display the localized text based on the current locale.
Text Direction: LTR and RTL
While most languages are written Left-to-Right (LTR), some, like Arabic, are written Right-to-Left (RTL). Flutter automatically adjusts text direction based on the selected locale, but you may need to make additional layout adjustments for RTL languages.
Advanced Features
Flutter’s gen_l10n
tool offers advanced features such as escaping syntax for special characters, handling plurals, and overriding locales within specific parts of the widget tree. Refer to the official Flutter documentation for more details on these features.
Change App Language Programmatically
To incorporate a manual language switcher in your app, set the selected language as a locale property to the MaterialApp
widget. Here’s an example:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
locale: Locale('es'), // Set to Spanish for example
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MyHomePage(),
);
}
}
Managing Localization with Localizely
As your app grows, managing localization files manually can become cumbersome. Tools like Localizely help automate this process.
Step 1: Create a Project in Localizely
Sign up on Localizely and create a new project. Set your main language and add other languages as needed.
Step 2: Upload Your Files
Upload your main .arb
file to Localizely. This file will serve as the basis for your translations.
Step 3: Invite Team Members
Localization is a team effort. Add team members to your project and assign them roles and languages to work on.
Step 4: Translate
Use Localizely’s editor to manage and translate your app’s text strings.
Step 5: Download the Files
After translating, download the updated .arb
files from Localizely and replace the existing files in your Flutter project.
Text Direction: Left-to-Right and Right-to-Left
Although most languages are written Left-to-Right (LTR), it is important to be aware that there are also Right-to-Left (RTL) languages. In this guide, we have included Arabic, which is an RTL language. Whenever the app is opened in Arabic, the layout should change accordingly. Generally, the Flutter framework updates the text direction within the app to correspond to the selected locale. In most cases, no adjustments are necessary. However, if the layout is designed exclusively for LTR languages or uses some hard-coded values, there is a possibility it may not display correctly. Be aware that adding an RTL language like Arabic to your app might also necessitate changes to your layout.
Escaping Syntax
Typically, the content of localization messages is straightforward. Nevertheless, on occasion, there is a need to incorporate messages with special characters, such as curly braces { and }. To prevent these tokens from being parsed, it is necessary to enable the use-escaping flag within the l10n.yaml file.
use-escaping: true
Once escaping is enabled, utilize single quotes to escape special characters in your localization messages.
{
"escapingExample": "In math, '{1, 2, 3}' denotes a set."
}
Avoid Null Checking
By default, getters in the generated localizations class are nullable. To eliminate the need for repeated null checks, you can turn off the nullable-getter option in the l10n.yaml file.
nullable-getter: false
After disabling nullable getters, you will be able to access the localization messages as shown below.
AppLocalizations.of(context).yourMessage
Get the Selected Locale
To get the selected locale of the widget tree, use the snippet shown below.
Locale selectedLocale = Localizations.localeOf(context);
Override the Locale
In some rare cases, you might want to override the locale of one part of the widget tree. For that purpose, you should use the Localizations.override factory constructor. Below, you can see an example where the helloWorld message is shown regularly and with an overridden locale.
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(AppLocalizations.of(context)!.helloWorld),
Localizations.override(
context: context,
locale: const Locale('es'),
// Using a Builder here to get the correct BuildContext.
child: Builder(
builder: (BuildContext context) {
return Text(AppLocalizations.of(context)!.helloWorld);
},
),
),
],
);
}
Conclusion
In this guide, we covered the essential steps to localize your Flutter app, from managing dependencies and configuring localization tools to handling text direction and managing translations with Localizely. By following these steps, you can ensure your app is accessible to a global audience, providing a better user experience and expanding your market reach. Embrace localization to make your app truly global. Hire iPhone App Developers to further enhance your app’s capabilities and reach.
Leave a comment