How to add localization to a Flutter application?
sobes.tech AI
Answer from AI
-
Adding dependencies:
In the
pubspec.yamlfile, add dependencies for localization:dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: ^0.18.0 # Example version, may varyThen run
flutter pub get. -
Creating localization files:
Create directories for localization resources, e.g.,
./lib/l10n/. Inside, create.arbfiles for each supported language. For example, for English and Russian:app_en.arb:{ "helloWorld": "Hello World!", "@@locale": "en" }app_ru.arb:{ "helloWorld": "Привет мир!", "@@locale": "ru" } -
Configuring code generation:
In the
pubspec.yamlfile, specify the path to localization files and configure.arbgeneration:flutter: generate: true # Enable generation assets: - assets/... # Your other assets l10n: arb-dir: lib/l10n # Directory with .arb files template-arb-file: app_en.arb # Template .arb file output-localization-file: app_localizations.dart # Name of generated fileAfter saving
pubspec.yaml, Flutter will automatically generate the file./lib/generated/l10n.dart(or the specifiedoutput-localization-file). -
Using localized strings:
In the app where you need to use localized strings, import the generated file:
import 'package:flutter_gen/gen_l10n/app_localizations.dart';Then access the localized string via
AppLocalizations.of(context)!:Text(AppLocalizations.of(context)!.helloWorld), -
Configuring
MaterialApporCupertinoApp:In the top-level widget (usually
MaterialApporCupertinoApp), specify language support and localization delegates:import 'package:flutter_gen/gen_l10n/app_localizations.dart'; MaterialApp( // ... other settings localizationsDelegates: const [ AppLocalizations.delegate, // Delegate from generated file GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), // English Locale('ru', ''), // Russian // ... other supported languages ], // ... );
Now the app will automatically select localization based on the user's device settings if available in supportedLocales. To manually change the locale, you can use Locale and update the app state.