To configure localization add the following to the pubspec.yaml
file. The file should look like below.
dependencies:
# ..
flutter_localizations:
sdk: flutter
# Localization Packages
intl: any
flutter:
generate: true
Make sure to add the generate: true
flag under flutter
.
The localization files can be placed under lib/l10n
folder with name app_en.arb
with key value pair format for its content.
{
"appTitle": "Flutter App"
}
Now we need to generate the localization classes from the strings defined. For that we can use the command flutter gen-l10n
. But we can configure Flutter to automatically generate this file by creating an l10n.yaml
file in the root directory with the following content.
# auto generate localization file
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
With this we don't have to run flutter gen-l10n
command each time we make changes to the arb
file or in CI/CD build steps.
Now in the app initialization widget specify the localization details.
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
// ..
child: MaterialApp.router(
// ..
supportedLocales: AppLocalizations.supportedLocales,
localizationsDelegates: AppLocalizations.localizationsDelegates,
),
We can also add helper extension context_extensions.dart
to easily access localization strings.
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
extension ContextExtensions on BuildContext {
@pragma('vm:prefer-inline')
AppLocalizations get loc => AppLocalizations.of(this)!;
}
Now we can access the localized strings from the BuildContext
like:
@override
Widget build(BuildContext context) {
var strings = context.loc;
print(strings.appTitle);
}