In today’s globalized world, creating applications that cater to a diverse audience is essential. Internationalization (i18n) and localization (l10n) are critical processes for making your app accessible and appealing to users from different countries and cultures. This article will guide you through the steps to internationalize and localize your Flutter applications.
What is Internationalization (i18n) and Localization (l10n)?
- Internationalization (i18n): Designing and developing an application so that it can be adapted to various languages and regions without engineering changes.
- Localization (l10n): Adapting an internationalized application for a specific language or region by adding locale-specific components and translating text.
Why Internationalize and Localize Your Flutter Apps?
- Expanded Reach: Increase your potential user base by supporting multiple languages.
- Improved User Experience: Users prefer applications in their native language.
- Competitive Advantage: Differentiate your app by offering a localized experience.
Steps to Internationalize and Localize Flutter Applications
Step 1: Add the flutter_localizations
Dependency
First, you need to add the flutter_localizations
and intl
dependencies to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0 # Use the latest version
Then, run flutter pub get
to install the dependencies.
Step 2: Configure MaterialApp
for Localization
In your main.dart
file, configure the MaterialApp
to support localization by setting the localizationsDelegates
, supportedLocales
, and localeResolutionCallback
properties:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Localization Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'), // English, United States
const Locale('es', 'ES'), // Spanish, Spain
],
localeResolutionCallback: (locale, supportedLocales) {
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale?.languageCode &&
supportedLocale.countryCode == locale?.countryCode) {
return supportedLocale;
}
}
// If the locale is not explicitly supported, fallback to the first supported locale
return supportedLocales.first;
},
home: MyHomePage(title: 'Flutter Localization Demo'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Hello World',
style: TextStyle(fontSize: 20),
),
],
),
),
);
}
}
In this code:
localizationsDelegates
: Provides the delegates for the localization.supportedLocales
: Lists the locales that your app supports.localeResolutionCallback
: Determines which locale to use if the user’s locale is not directly supported.
Step 3: Create Localization Files
Next, create localization files for each supported locale. These files will contain the translations for your app’s text. A common approach is to use ARB (Application Resource Bundle) files.
Create a new directory named l10n
in the root of your Flutter project.
For English (l10n/app_en.arb
):
{
"helloWorld": "Hello World",
"@helloWorld": {
"description": "The conventional newborn programmer greeting"
}
}
For Spanish (l10n/app_es.arb
):
{
"helloWorld": "Hola Mundo",
"@helloWorld": {
"description": "El saludo convencional del programador recién nacido"
}
}
Step 4: Generate Localized Code
Flutter provides a tool to generate Dart code from ARB files, which makes it easy to access the localized strings. First, add the intl_utils
package as a dev dependency:
dev_dependencies:
flutter_test:
sdk: flutter
intl_utils: ^2.7.0 # Use the latest version
Next, update your pubspec.yaml
file to include a flutter
section with configuration for localization:
flutter:
generate: true
Now, run the following command in the terminal to generate the localization code:
flutter gen-l10n
This command generates a file named app_localizations.dart
in the lib
directory. This file contains the AppLocalizations
class, which provides access to the localized strings.
Step 5: Use Localized Strings in Your App
Now that you have generated the AppLocalizations
class, you can use it to display localized strings in your app.
Update main.dart
to use AppLocalizations
:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Localization Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: [
AppLocalizations.delegate, // Add this line
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'), // English, United States
const Locale('es', 'ES'), // Spanish, Spain
],
localeResolutionCallback: (locale, supportedLocales) {
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale?.languageCode &&
supportedLocale.countryCode == locale?.countryCode) {
return supportedLocale;
}
}
// If the locale is not explicitly supported, fallback to the first supported locale
return supportedLocales.first;
},
home: MyHomePage(title: 'Flutter Localization Demo'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
AppLocalizations.of(context)!.helloWorld, // Use localized string
style: TextStyle(fontSize: 20),
),
],
),
),
);
}
}
In this example, AppLocalizations.of(context)!.helloWorld
retrieves the localized “Hello World” string based on the current locale.
Step 6: Testing Localization
To test your localization settings, you can change the device’s locale or use the --locale
argument when running your app:
flutter run --locale es_ES
Advanced Localization Techniques
- Pluralization: Handling different forms of a word based on quantity.
- Gender Adaptation: Adapting text based on the gender of the user.
- Date and Time Formatting: Displaying dates and times in locale-specific formats.
- Currency Formatting: Displaying currency values in locale-specific formats.
Tips for Successful Internationalization and Localization
- Plan Ahead: Consider internationalization from the beginning of your project.
- Use Externalization: Keep all text and locale-specific resources separate from your code.
- Test Thoroughly: Test your app in multiple locales and languages.
- Use Professional Translators: Ensure high-quality translations by hiring professional translators.
- Consider Cultural Differences: Be aware of cultural nuances and adapt your app accordingly.
Conclusion
Internationalizing and localizing your Flutter applications can significantly enhance user experience and broaden your app’s reach. By following these steps and adopting best practices, you can create apps that appeal to users worldwide, driving engagement and success in diverse markets. Properly internationalizing and localizing a Flutter app not only enhances user experience but also expands its global accessibility, ensuring relevance and acceptance across different cultural contexts.