azbox 1.0.8 copy "azbox: ^1.0.8" to clipboard
azbox: ^1.0.8 copied to clipboard

Easy and fast internationalization for your Flutter Apps. Translate your apps using AZBox.

Easy and Fast internationalization for your Flutter Apps

Pub Version Code Climate issues GitHub closed issues GitHub contributors GitHub repo size GitHub forks GitHub stars Coveralls github branch GitHub Workflow Status CodeFactor Grade GitHub license

Why Azbox? #

  • 🚀 Easy translations for many languages
  • 🔌 Load translations as JSON, CSV, Yaml, Xml
  • 💾 React and persist to locale changes
  • ⚡ Supports gender, nesting, RTL locales and more
  • â†Šī¸ Fallback locale keys redirection
  • â‰ī¸ Error widget for missing translations
  • â¤ī¸ Extension methods on Text and BuildContext
  • đŸ’ģ Code generation for localization files and keys.
  • đŸ›Ąī¸ Null safety
  • đŸ–¨ī¸ Customizable logger.

Getting Started #

🔩 Installation #

Add to your pubspec.yaml:

dependencies:
  azbox-localization: <last_version>

âš™ī¸ Configuration app #

Add Azbox widget like in example

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:azbox/azbox.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Azbox.ensureInitialized(
    apiKey: 'Your API Key',
    projectId: 'Your project ID');
  
  runApp(
    Azbox(
      child: MyApp()
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      home: MyHomePage()
    );
  }
}

Full example

📜 Azbox localization widget properties #

Properties Required Default Description
key false Widget key.
child true Place for your main page widget.
startLocale false Overrides device locale.
saveLocale false true Save locale in device storage.
useFallbackTranslations false false If a localization key is not found in the locale file, try to use the fallbackLocale file.

Usage #

đŸ”Ĩ Initialize library #

Call Azbox.ensureInitialized() in your main before runApp.

void main() async{

  WidgetsFlutterBinding.ensureInitialized();
  
  // ...
  // Needs to be called so that we can await for Azbox.ensureInitialized();
  await Azbox.ensureInitialized(
    apiKey: 'Your API Key',
    projectId: 'Your project ID');
    
  // ...
  runApp(....)
  // ...
}

đŸ”Ĩ Change or get locale #

Azbox localization uses extension methods [BuildContext] for access to locale.

It's the easiest way change locale or get parameters 😉.

â„šī¸ No breaking changes, you can use old the static method Azbox.of(context)

Example:

context.setLocale(Locale('en', 'US'));

print(context.locale.toString());

đŸ”Ĩ Translate translate() #

Main function for translate your language keys

You can use extension methods of [String] or [Text] widget, you can also use translate() as a static function.

Text('title').translate() //Text widget

print('title'.translate()); //String

var title = translate('title') //Static function

Text(context.translate('title')) //Extension on BuildContext

Arguments:

Name Type Description
args List<String> List of localized strings. Replaces {} left to right
namedArgs Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
gender String Gender switcher. Changes the localized string based on gender string

Example:

{
   "msg":"{} are written in the {} language",
   "msg_named":"Azbox localization is written in the {lang} language",
   "msg_mixed":"{} are written in the {lang} language",
   "gender":{
      "male":"Hi man ;) {}",
      "female":"Hello girl :) {}",
      "other":"Hello {}"
   }
}
// args
Text('msg').translate(args: ['Azbox localization', 'Dart']),

// namedArgs
Text('msg_named').translate(namedArgs: {'lang': 'Dart'}),

// args and namedArgs
Text('msg_mixed').translate(args: ['Azbox localization'], namedArgs: {'lang': 'Dart'}),

// gender
Text('gender').translate(gender: _gender ? "female" : "male"),

đŸ”Ĩ Linked translations: #

If there's a translation key that will always have the same concrete text as another one you can just link to it. To link to another translation key, all you have to do is to prefix its contents with an @: sign followed by the full name of the translation key including the namespace you want to link to.

Example:

{
  ...
  "example": {
    "hello": "Hello",
    "world": "World!",
    "helloWorld": "@:example.hello @:example.world"
  }
  ...
}
print('example.helloWorld'.translate()); //Output: Hello World!

You can also do nested anonymous and named arguments inside the linked messages.

Example:

{
  ...
  "date": "{currentDate}.",
  "dateLogging": "INFO: the date today is @:date"
  ...
}
print('dateLogging'.translate(namedArguments: {'currentDate': DateTime.now().toIso8601String()})); //Output: INFO: the date today is 2020-11-27T16:40:42.657.

Formatting linked translations:

Formatting linked locale messages If the language distinguishes cases of character, you may need to control the case of the linked locale messages. Linked messages can be formatted with modifier @.modifier:key

The below modifiers are available currently.

  • upper: Uppercase all characters in the linked message.
  • lower: Lowercase all characters in the linked message.
  • capitalize: Capitalize the first character in the linked message.

Example:

{
  ...
  "example": {
    "fullName": "Full Name",
    "emptyNameError": "Please fill in your @.lower:example.fullName"
  }
  ...
}

Output:

print('example.emptyNameError'.translate()); //Output: Please fill in your full name

đŸ”Ĩ Reset locale resetLocale() #

Reset locale to device locale

Example:

RaisedButton(
  onPressed: (){
    context.resetLocale();
  },
  child: Text(LocaleKeys.reset_locale).translate(),
)

đŸ”Ĩ Get device locale deviceLocale #

Get device locale

Example:

print(${context.deviceLocale.toString()}) // OUTPUT: en_US

đŸ”Ĩ Delete save locale deleteSaveLocale() #

Clears a saved locale from device storage

Example:

RaisedButton(
  onPressed: (){
    context.deleteSaveLocale();
  },
  child: Text(LocaleKeys.reset_locale).translate(),
)

đŸ”Ĩ Get Azbox localization widget properties #

At any time, you can take the main properties of the Azbox localization widget using [BuildContext].

Are supported: supportedLocales, localizationDelegates.

Example:

print(context.supportedLocales); // output: [en_US, ar_DZ, de_DE, ru_RU]

đŸ’ģ Code generation #

Code generation supports only json files, for more information run in terminal flutter pub run azbox_localization:generate -h

Command line arguments #

Arguments Short Default Description
--help -h Help info
--source-dir -S resources/langs Folder containing localization files
--source-file -s First file File to use for localization
--output-dir -O lib/generated Output folder stores for the generated file
--output-file -o codegen_loader.g.dart Output file name
--format -f json Support json or keys formats
--[no-]skip-unnecessary-keys -u false Ignores keys defining nested object except for pluarl(), gender() keywords.

🔌 Localization asset loader class #

Steps:

  1. Open your terminal in the folder's path containing your project
  2. Run in terminal flutter pub run azbox_localization:generate
  3. Change asset loader and past import.
import 'generated/codegen_loader.g.dart';
...
void main(){
  runApp(Azbox(
    child: MyApp(),
  ));
}
...
  1. All done!

🔑 Localization keys #

If you have many localization keys and are confused, key generation will help you. The code editor will automatically prompt keys

Steps:

  1. Open your terminal in the folder's path containing your project
  2. Run in terminal flutter pub run azbox_localization:generate -f keys -o locale_keys.g.dart
  3. Past import.
import 'generated/locale_keys.g.dart';
  1. All done!

How to use generated keys:

print(LocaleKeys.title.translate()); //String
//or
Text(LocaleKeys.title).translate(); //Widget

➕ Extensions helpers #

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
4
likes
50
points
51
downloads

Publisher

unverified uploader

Weekly Downloads

Easy and fast internationalization for your Flutter Apps. Translate your apps using AZBox.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

async, flutter, flutter_localizations, hive_flutter, http, intl, path_provider

More

Packages that depend on azbox