Adding Multilingual Support to Your Flutter App Want your app to speak different languages? Let’s make it happen!
1. Set Up the Packages:
Add flutter_localizations: This package handles localization.
Add intl: This package provides internationalization utilities.
2. Configure Localization:
Enable code generation: In your pubspec.yaml file, set generate: true under the flutter section.
Create a configuration file: Name it l10n.yaml and put it in your project’s root directory. The file should look like this:
arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart
Use code with caution.
This tells Flutter where to find your language files and where to generate the localization code.
3. Create Language Files:
English template: Create a file named app_en.arb in the lib/l10n directory. This is your base language file.
{ "helloWorld": "Hello World!" }
Use code with caution.
Additional languages: Create files for other languages (e.g., app_es.arb for Spanish). Translate the messages.
4. Generate Localization Code:
Run the command: Execute flutter pub get or flutter run to trigger code generation. You’ll find the generated files in
.dart_tool/flutter_gen/gen_l10n.
5. Use Localization in Your App:
Import: Import app_localizations.dart in your main file.
Add delegates: In your MaterialApp, add AppLocalizations.delegate and other necessary delegates to the localizationsDelegates list.
Use localization: Access localized strings using AppLocalizations.of(context)!.messageName.
Example:
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // ... return const MaterialApp( // ... localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, // ... );
Use code with caution.
And that’s it! Your app can now adapt to different languages based on the user’s device settings.