flutter_translaty 1.0.12 flutter_translaty: ^1.0.12 copied to clipboard
Manage your translations easily with translaty.io. Built on top of easy_localization
Welcome to flutter_translaty #
This package allows you to use your translations managed in www.translaty.io in your Flutter app easily.
Thanks to easy_localization #
Translaty relies on the open source solution https://pub.dev/packages/easy_localization for integrating translations into Flutter. We are very grateful to the maintainers and appreciate their hard work to develop this great tool. This package is a fork of easy_localization, enriched with Translaty-specific features like Over-The-Air-Update.
Get started #
Translaty Setup #
If not done yet, create a project at www.translaty.io. Translaty already created a first translation key called "hello_world" for you. If you want, modify it.
In the project settings, you can copy a client key to your clipboard
[Get client key]
Flutter Setup #
- Install the flutter_translaty package:
flutter pub add flutter_translaty
Run the setup-command and pass your key. It will create a file called translaty.yaml in your project root with the relevant content.
flutter pub run flutter_translaty:setup --key "<<your_client_key>>"
Run the command to generate your translation files
flutter pub run flutter_translaty:generate
Add assets/translations/ and translaty.yaml as asset-paths to your pubspec.yaml
flutter:
assets:
- translaty.yaml
- assets/translations/
In the beginning of your main() method in main.dart, add:
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
Wrap your app with an EasyLocalization widget like this. Make sure to use the locales you added while creating your project. Keep in mind that Locale("en") is not the same as Locale("en", "US").
// before
runApp(const MyApp());
// after
runApp(
EasyLocalization(
supportedLocales: const [
Locale('en', 'US'),
Locale('de'),
],
path: 'assets/translations',
fallbackLocale: const Locale('en', 'US'),
saveLocale: true,
child: const MyApp(),
),
);
Add the necessary attributes to your MaterialApp
// Before
return MaterialApp(
home: const MyHomePage()
);
// After
return MaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home: const MyHomePage()
);
To test if it's working, add some text widget
Text(tr(LocaleKeys.hello_world)),
You will have to make some import statements for the above things to work, e.g.
import 'package:flutter/material.dart';
import 'package:flutter_translaty/flutter_translaty.dart';
import 'generated/locale_keys.g.dart';
If you run your app now, you should see the "hello world" text from Translaty.
(optional) Add buttons for changing the language #
Add a button for changing the language. This sample code uses the 'de'-locale, you can replace that with any other locale that your project supports.
ElevatedButton(
onPressed: () {
final locales = context.supportedLocales;
if (locales.length == 1) {
print(
"Can't change the locale when you have only one locale");
return;
}
final anotherLocale = locales.firstWhere(
(element) => element != context.locale,
);
context.setLocale(anotherLocale);
},
child: const Text("Change language"),
),
Arguments #
Add a key in Translaty and insert an argument with curly braces
[create key with arg]
Fill the text for all languages
[key with arg]
Re-generate the translations in your flutter project
flutter pub run flutter_translaty:generate
Use the arguments like this:
Text(
tr(LocaleKeys.key_with_args, namedArgs: {
"toolName": "Translaty",
}),
)
Plurals #
Add a key and tick "plural" in Translaty
[Create plural key]
Fill the plural cases for all languages
[plural key]
Re-generate the translations in your flutter project
flutter pub run flutter_translaty:generate
Use the plural key like this:
Text(plural(LocaleKeys.some_plural_key, 3))
Testing #
Normally, you don't have to worry about Translaty when you perform testing. However, the package makes real https-calls (to fetch the config and to do Over-The-Air-Updates. If you want to avoid that, you can create a mock of the OtaService. Here is an example using mocktail:
import 'package:mocktail/mocktail.dart'
class MockOtaService extends Mock implements OtaService {}
final mockOtaService = MockOtaService();
when(() => mockOtaService.init()).thenAnswer((_) => Future.value());
when(() => mockOtaService.shallExecuteOta).thenReturn(false);
Then, pass this mock to your EasyLocalization-Widget
EasyLocalization(
otaService: mockOtaService,
)
Logging #
easy_localization uses a logger based on https://pub.dev/packages/easy_logger
You can customize the logger for you project
Show only lost keys message #
Lost translations keys logged like warning messages. Change [Easy Logger] level for display only errors and warnings.
EasyLocalization.logger.enableLevels = [LevelMessages.error, LevelMessages.warning];
Logger off #
For disable logger, change Build Modes in [Easy Logger] to empty List;
EasyLocalization.logger.enableBuildModes = [];
Catching logger messages #
For catching logger messages you need override default printer function.
EasyLogPrinter customLogPrinter = (
Object object, {
String name,
StackTrace stackTrace,
LevelMessages level,
}) {
///Your function
print('$name: ${object.toString()}');
};
/// override printer to custom
EasyLocalization.logger.printer = customLogPrinter;
Read more about Easy Logger
Other features that easy_localization provides #
Get device locale deviceLocale
#
Get device locale
Example:
print(${context.deviceLocale.toString()}) // OUTPUT: en_US
Be careful! Maybe you added "en" as a language in Translaty, but your device locale is "en_US". In that case, you need to make the transformation manually.
Delete save locale deleteSaveLocale()
#
Clears a saved locale from device storage
Example:
ElevatedButton(
onPressed: (){
context.deleteSaveLocale();
},
child: Text(LocaleKeys.reset_locale).tr(),
)
String to locale #
'en_US'.toLocale(); // Locale('en', 'US')
//with custom separator
'en|US'.toLocale(separator: '|') // Locale('en', 'US')
Locale to String with separator #
Locale('en', 'US').toStringWithSeparator(separator: '|') // en|US