To connect localization to a Flutter app, you need to follow a series of steps to ensure your app can support multiple languages and cultural preferences. Here's a detailed guide on how to set up localization in a Flutter app:
Step-by-Step Guide to Flutter Localization
- Add Dependencies:
- First, you need to add the necessary dependencies to your
pubspec.yaml
file. Include theflutter_localizations
andintl
packages. These packages provide the necessary tools for localization and internationalization.
yamlWrapCopy1dependencies:2flutter:3sdk: flutter4flutter_localizations:5sdk: flutter6intl: ^0.17.0
- First, you need to add the necessary dependencies to your
- Configure ARB Files:
- Flutter uses ARB (Application Resource Bundle) files to store translations. Create a directory named
l10n
in your project root and add ARB files for each language you want to support, such asapp_en.arb
for English andapp_es.arb
for Spanish. These files contain key-value pairs for each translatable string.
jsonWrapCopy1{2"@@locale": "en",3"title": "Hello World",4"message": "Welcome to Flutter localization"5}
- Flutter uses ARB (Application Resource Bundle) files to store translations. Create a directory named
- Generate Localization Files:
- Use the
flutter gen-l10n
command to generate Dart localization files from your ARB files. This command will create agenerated
directory with the necessary Dart files for localization.
- Use the
- Modify
main.dart
:- Update your
main.dart
file to include localization delegates and supported locales. Modify theMaterialApp
widget to use these settings.
dartWrapCopy1import 'package:flutter/material.dart';2import 'package:flutter_localizations/flutter_localizations.dart';3import 'generated/l10n.dart';45void main() {6runApp(MyApp());7}89class MyApp extends StatelessWidget {10@override11Widget build(BuildContext context) {12return MaterialApp(13localizationsDelegates: [14AppLocalizations.delegate,15GlobalMaterialLocalizations.delegate,16GlobalWidgetsLocalizations.delegate,17],18supportedLocales: [19const Locale('en', ''), // English20const Locale('es', ''), // Spanish21],22home: MyHomePage(),23);24}25}
- Update your
- Use Localized Strings:
- In your widgets, use the generated localization class to access localized strings. For example, use
AppLocalizations.of(context).title
to get the localized title.
dartWrapCopy1class MyHomePage extends StatelessWidget {2@override3Widget build(BuildContext context) {4return Scaffold(5appBar: AppBar(6title: Text(AppLocalizations.of(context).title),7),8body: Center(9child: Text(AppLocalizations.of(context).message),10),11);12}13}
- In your widgets, use the generated localization class to access localized strings. For example, use
- Test Your App:
- Run your app and test it by changing the device's language settings. Ensure that the app displays the correct translations for each supported language.
Only for Supporters
To read the rest of this article and access other paid content, you must be a supporter