flutter_translate library
the internationalization (i18n) library for flutter.
it lets you define translations for your content in different languages and switch between them easily.
installation
add this to your package’s pubspec.yaml file:
dependencies:
flutter_translate: ^1.2.5
install packages from the command line (or from your editor):
flutter pub get
configuration
import flutter_translate:
import 'package:flutter_translate/flutter_translate.dart';
place the json localization files in a folder of your choice within the project.
by default flutter_translate
will search for localization files in the assets/i18n
directory in your project’s root.
declare your assets localization directory in pubspec.yaml
flutter:
assets:
- assets/i18n
in the main function create the localization delegate and start the app, wrapping it with localizedapp
void main() async
{
var delegate = await localizationdelegate.create(
fallbacklanguage: 'en',
supportedlanguages: ['en', 'es_es', 'fa']);
runapp(localizedapp(delegate, myapp()));
}
if the assets directory for the localization files is different than the default one (assets/i18n
), you need to specify it:
void main() async
{
var delegate = await localizationdelegate.create(
fallbacklanguage: 'en',
supportedlanguages: ['en', 'es_es', 'fa'],
basepath: 'assets/i18n/');
runapp(localizedapp(delegate, myapp()));
}
example myapp:
class myapp extends statelesswidget {
@override
widget build(buildcontext context) {
var localizationdelegate = localizedapp.of(context).delegate;
return localizationprovider(
state: localizationprovider.of(context).state,
child: materialapp(
title: 'flutter translate demo',
localizationsdelegates: [
globalmateriallocalizations.delegate,
globalwidgetslocalizations.delegate,
localizationdelegate
],
supportedlocales: localizationdelegate.configuration.supportedlocales,
locale: localizationdelegate.currentlocale,
theme: themedata(primaryswatch: colors.blue),
home: myhomepage(),
),
);
}
}
usage
translate a string:
translate('your.localization.key');
translate with arguments;
translate('your.localization.key', args: {'argname1': argvalue1, 'argname2': argvalue2});
translate with pluralization:
translateplural('plural.demo', yournumericvalue);
json:
"plural": {
"demo": {
"0": "please start pushing the 'plus' button.",
"1": "you have pushed the button one time.",
"else": "you have pushed the button {{value}} times."
}
}
change the language:
@override
widget build(buildcontext context) {
...
...
changelanguage(context, 'en');
...
...
}
you can view the full example here:
https://github.com/bratan/flutter_translate/blob/master/example/lib/main.dart
Comments are closed.