intl 0.15.1

Intl

This package provides internationalization and localization facilities, including message translation, plurals and genders, date/number formatting and parsing, and bidirectional text.

General

The most important library is intl. It defines the Intl class, with the default locale and methods for accessing most of the internationalization mechanisms. This library also defines the DateFormat, NumberFormat, and BidiFormatter classes.

Current locale

The package has a single current locale, called defaultLocale. Operations will use that locale unless told to do otherwise.

You can explicitly set the global locale

  Intl.defaultLocale = 'pt_BR';

or get it from the browser

  import "package:intl/intl_browser.dart";
  ...
  findSystemLocale().then(runTheRestOfMyProgram);

To override the current locale for a particular operation, pass the operation to withLocale. Note that this includes async tasks spawned from that operation, and that the argument to withLocale will supercede the defaultLocale while the operation is active. If you are using different locales within an application, the withLocale operation may be preferable to setting defaultLocale.

  Intl.withLocale('fr', () => print(myLocalizedMessage());

To specify the locale for an operation you can create a format object in a specific locale, pass in the locale as a parameter to methods, or set the default locale.

var format = new DateFormat.yMd("ar");
var dateString = format.format(new DateTime.now());

or

print(myMessage(dateString, locale: 'ar');

or

Intl.defaultLocale = "es";
new DateFormat.jm().format(new DateTime.now());

Initialization

All the different types of locale data require an async initialization step to make sure the data is available. This reduces the size of the application by only loading the data that is actually required.

Each different area of internationalization (messages, dates, numbers) requires a separate initialization process. That way, if the application only needs to format dates, it doesn't need to take the time or space to load up messages, numbers, or other things it may not need.

With messages, there is also a need to import a file that won't exist until the code generation step has been run. This can be awkward, but can be worked around by creating a stub messages_all.dart file, running an empty translation step, or commenting out the import until translations are available. See "Extracting and Using Translated Messages"

Messages

Messages to be localized are written as functions that return the result of an Intl.message call.

  String continueMessage() => Intl.message(
      "Hit any key to continue",
      name: "continueMessage",
      args: [],
      desc: "Explains that we will not proceed further until "
          "the user presses a key");
  print(continueMessage());

This provides, in addition to the basic message string, a name, a description for translators, the arguments used in the message, and examples. The name and args parameters are required, and must match the name (or ClassName_methodName) and arguments list of the function respectively. However, there is a transformer provided that will automatically insert those parameters for you. In pubspec.yaml, add a section like

  transformers:
  - intl:
  $include: some_file.dart

and then you can omit the name and args.

A function with an Intl.message call can be run in the program before any translation has been done, and will just return the message string. It can also be extracted to a file and then be made to return a translated version without modifying the original program. See "Extracting Messages" below for more details.

The purpose of wrapping the message in a function is to allow it to have parameters which can be used in the result. The message string is allowed to use a restricted form of Dart string interpolation, where only the function's parameters can be used, and only in simple expressions. Local variables cannot be used, and neither can expressions with curly braces. Only the message string can have interpolation. The name, desc, args, and examples must be literals and not contain interpolations. Only the args parameter can refer to variables, and it should list exactly the function parameters. If you are passing numbers or dates and you want them formatted, you must do the formatting outside the function and pass the formatted string into the message.

  greetingMessage(name) => Intl.message(
      "Hello $name!",
      name: "greetingMessage",
      args: [name],
      desc: "Greet the user as they first open the application",
      examples: const {'name': "Emily"});
  print(greetingMessage('Dan'));

There is one special class of complex expressions allowed in the message string, for plurals and genders.

  remainingEmailsMessage(int howMany, String userName) =>
    Intl.message(
      "${Intl.plural(howMany,
          zero: 'There are no emails left for $userName.',
          one: 'There is one email left for $userName.',
          other: 'There are $howMany emails left for $userName.')}",
    name: "remainingEmailsMessage",
    args: [howMany, userName],
    desc: "How many emails remain after archiving.",
    examples: const {'howMany': 42, 'userName': 'Fred'});

  print(remainingEmailsMessage(1, "Fred"));

However, since the typical usage for a plural or gender is for it to be at the top-level, we can also omit the Intl.message call and provide its parameters to the Intl.plural call instead.

  remainingEmailsMessage(int howMany, String userName) =>
    Intl.plural(
      howMany,
      zero: 'There are no emails left for $userName.',
      one: 'There is one email left for $userName.',
      other: 'There are $howMany emails left for $userName.',
      name: "remainingEmailsMessage",
      args: [howMany, userName],
      desc: "How many emails remain after archiving.",
      examples: const {'howMany': 42, 'userName': 'Fred'});

Similarly, there is an Intl.gender message, and plurals and genders can be nested.

  notOnlineMessage(String userName, String userGender) =>
    Intl.gender(
      userGender,
      male: '$userName is unavailable because he is not online.',
      female: '$userName is unavailable because she is not online.',
      other: '$userName is unavailable because they are not online',
      name: "notOnlineMessage",
      args: [userName, userGender],
      desc: "The user is not available to hangout.",
      examples: const {{'userGender': 'male', 'userName': 'Fred'},
          {'userGender': 'female', 'userName' : 'Alice'}});

It's recommended to use complete sentences in the sub-messages to keep the structure as simple as possible for the translators.

Extracting And Using Translated Messages

When your program contains messages that need translation, these must be extracted from the program source, sent to human translators, and the results need to be incorporated. The code for this is in the [Intl_translation][Intl_translation] package.

To extract messages, run the extract_to_arb.dart program.

  pub run intl_translation:extract_to_arb --output-dir=target/directory
      my_program.dart more_of_my_program.dart

This will produce a file intl_messages.arb with the messages from all of these programs. an [ARB] (https://code.google.com/p/arb/wiki/ApplicationResourceBundleSpecification) format file which can be used for input to translation tools like Google Translator Toolkit The resulting translations can be used to generate a set of libraries using the generate_from_arb.dart program.

This expects to receive a series of files, one per locale.

pub run intl_translation:generate_from_arb --generated_file_prefix=<prefix>
    <my_dart_files> <translated_ARB_files>

This will generate Dart libraries, one per locale, which contain the translated versions. Your Dart libraries can import the primary file, named <prefix>messages_all.dart, and then call the initialization for a specific locale. Once that's done, any Intl.message calls made in the context of that locale will automatically print the translated version instead of the original.

  import "my_prefix_messages_all.dart";
  ...
  initializeMessages("dk").then(printSomeMessages);

Once the future returned from the initialization call returns, the message data is available.

Number Formatting and Parsing

To format a number, create a NumberFormat instance.

  var f = new NumberFormat("###.0#", "en_US");
  print(f.format(12.345));
    ==> 12.34

The locale parameter is optional. If omitted, then it will use the current locale. The format string is as described in NumberFormat

It's also possible to access the number symbol data for the current locale, which provides information as to the various separator characters, patterns, and other information used for formatting, as

  f.symbols

Current known limitations are that the currency format will only print the name of the currency, and does not support currency symbols, and that the scientific format does not really agree with scientific notation. Number parsing is not yet implemented.

Note that before doing any number formatting for a particular locale you must load the appropriate data by calling

  import 'package:intl/number_symbols_data_local.dart';
  ...
  initializeNumberFormatting(localeName, null).then(formatNumbers);

Once the future returned from the initialization call returns, the formatting data is available. Note that right now this includes all the data for a locales. We expect to make this use deferred loading to reduce code size.

Date Formatting and Parsing

To format a DateTime, create a DateFormat instance. These can be created using a set of commonly used skeletons taken from ICU/CLDR or using an explicit pattern. For details on the supported skeletons and patterns see DateFormat.

  new DateFormat.yMMMMEEEEd().format(aDateTime);
    ==> 'Wednesday, January 10, 2012'
  new DateFormat("EEEEE", "en_US").format(aDateTime);
    ==> 'Wednesday'
  new DateFormat("EEEEE", "ln").format(aDateTime);
    ==> 'mokɔlɔ mwa mísáto'

You can also parse dates using the same skeletons or patterns.

    new DateFormat.yMd("en_US").parse("1/10/2012");
    new DateFormat("Hms", "en_US").parse('14:23:01');

Skeletons can be combined, the main use being to print a full date and time, e.g.

    new DateFormat.yMEd().add_jms().format(new DateTime.now());
      ==> 'Thu, 5/23/2013 10:21:47 AM'

Known limitations: Time zones are not yet supported. Dart DateTime objects don't have a time zone, so are either local or UTC. Formatting and parsing Durations is not yet implemented.

Note that before doing any DateTime formatting for a particular locale, you must load the appropriate data by calling.

    import 'package:intl/date_symbol_data_local.dart';
    ...
    initializeDateFormatting("de_DE", null).then(formatDates);

Once the future returned from the initialization call returns, the formatting data is available.

There are other mechanisms for loading the date formatting data implemented, but we expect to deprecate those in favor of having the data in a library as in the above, and using deferred loading to only load the portions that are needed. For the time being, this will include all of the data, which will increase code size.

Bidirectional Text

The class BidiFormatter provides utilities for working with Bidirectional text. We can wrap the string with unicode directional indicator characters or with an HTML span to indicate direction. The direction can be specified with the RTL and LTR constructors, or detected from the text.

    new BidiFormatter.RTL().wrapWithUnicode('xyz');
    new BidiFormatter.RTL().wrapWithSpan('xyz');

0.15.1

  • Use the platform.locale API to get the OS platform.
  • Convert to use package:test

0.15.0

  • Fix compactCurrency to correctly use passed-in symbol.
  • A tweak to the way we retry on DateTime.asDate to compensate for a VM bug.
  • Update CLDR version to 30.
  • Cache the last result of isRtlLanguage
  • Some strong mode fixes
  • Allow passing enums to a select.
  • Remove the cacheBlocker parameter from HttpRequestDataReader
  • Optimize padding numbers when printing
  • Remove the out of date example directory
  • Add a facility to check if messages are being called before locale initialization, which can lead to errors if the results are being cached. See UninitializedLocaleData.throwOnFallback.
  • Restore dependency on path which was removed when intl_translation was separated.
  • Improve the error message when date parsing fails validation to show what the parsed date was.

0.14.0

  • MAJOR BREAKING CHANGE! Remove message extraction and code generation into a separate intl_translation package. This means packages with a runtime dependency on intl don't also depend on analyzer, barback, and so forth.

0.13.1

  • Update CLDR data to version 29.
  • Add a toBeginningOfSentenceCase() method which converts the first character of a string to uppercase. It may become more clever about that for locales with different conventions over time.
  • Fixed the use of currency-specific decimal places, which weren't being used if the currency was the default for the locale.
  • Add support for currency in compact number formats.
  • Added support for "Q" and "QQ" numeric quarter formatting, which fixes "QQQ" and "QQQQ" in the zh_CN locale.
  • As part of deprecating transformer usage, allow rewrite_intl_messages.dart to add names and arguments to messages with parameters. Make the transformer not generate names for zero-argument methods and just use the name+meaning instead.
  • Move barback from dev dependencies into public (see https://github.com/dart-lang/intl/issues/120 )

0.13.0

  • Add support for compact number formats ("1.2K") and for significant digits in number formats.
  • Add a NumberFormat.simpleCurrency constructor which will attempt to automatically determine the currency symbol. Very simple implementation but can be expanded to be per-locale.
  • Fix a problem where, in a message, a literal dollar sign followed by a number was seen as a valid identifier, resulting in invalid code being generated.
  • Add support for locale-specific plural rules. Note that this changes the interpretation of plurals and so is potentially breaking. For example, in English three will now be treated as "other" rather than as "few".
  • Add onMessage top level variable, which defaults to print. Warning and error messages will all now go through this function instead of calling print directly.
  • Move top-level variables in extract_messages.dart into a MessageExtraction object. This is a breaking change for code that imports extract_messages.dart, which probably only means message format readers/extractors like extract_to_arb.dart and generate_from_arb.dart.
  • Cache the message lookup for a locale, reducing unnecessary locale validation and lookup.

0.12.7+1

  • Change the signature for args and examples in Intl.plural/gender/select to match Intl.message, allowing dynamic values.
  • Parameters to initializeDateFormatting are optional.
  • Extend DateFormat.parseLoose() to allow arbitrary amounts of whitespace before literal fields (as well as after), and treat all whitespace around literal fields as optional even if the literal field's pattern has leading or trailing whitespace.
  • Fix DateFormat.parseLoose() returning unexpected values in certain cases where a pattern was missing from the input string.
  • Fix DateFormat.parseLoose() ignoring the value of numeric standalone months ('LL' pattern).
  • Remove relative imports on generate_locale_data_files.dart

0.12.7

  • Update SDK dependency to 1.12.0, to reflect use of null-aware operators.
  • Add a transformer to automatically add the "name" and "args" parameters to Intl.message and related calls. This removes a lot of tedious repetition.
  • Fix typo in README.
  • Make Intl strong-mode compatible.

0.12.6

  • Update links in README.md to point to current dartdocs.
  • Update locale data to CLDR 28.
  • Remove library directive from generated libraries. Conflicted with linter.
  • Support @@locale in ARB files as well as the older _locale
  • Print a message when generating from ARB files if we guess the locale from the file name when there's no explicit @@locale or _locale in the file.
  • Switch all the source to use line comments.
  • Slight improvement to the error message when parsing dates has an invalid value.
  • Introduce new NumberFormat.currency constructor which can explicitly take a separate currency name and symbol, as well as the number of decimal digits.
  • Provide a default number of decimal digits per-currency.
  • Deprecate NumberFormat.currencyPattern.

0.12.5

  • Parse Eras in DateFormat.
  • Update pubspec.yaml to allow newer version of fixnum and analyzer.
  • Improvements to the compiled size of generated messages code with dart2js.
  • Allow adjacent literal strings to be used for message names/descriptions.
  • Provide a better error message for some cases of bad parameters to plural/gender/select messages.
  • Introduce a simple MicroMoney class that can represent currency values scaled by a constant factor.

0.12.4+3

  • update analyzer to '<0.28.0' and fixnum to '<0.11.0'

0.12.4+2

  • update analyzer to '<0.27.0'

0.12.4+1

  • Allow the name of an Intl.message to be "ClassName_methodName", as well as "functionName". This makes it easier to disambiguate messages with the same name but in different classes.

0.12.4

  • Handle spaces in ARB files where we didn't handle them before, and where Google translation toolkit is now putting them.

0.12.3

  • Use latest version of 'analyzer' and 'args' packages.

0.12.2+1

  • Adds a special locale name "fallback" in verifiedLocale. So if a translation is provided for that locale and has been initialized, anything that doesn't find a closer match will use that locale. This can be used instead of having it default to the text in the original source messages.

0.12.1

  • Adds a DateFormat.parseLoose that accepts mixed case and missing delimiters when parsing dates. It also allows arbitrary amounts of whitespace anywhere that whitespace is expected. So, for example, in en-US locale a yMMMd format would accept "SEP 3 2014", even though it would generate "Sep 3, 2014". This is fairly limited, and its reliability in other locales is not known.

0.12.0+3

  • Update pubspec dependencies to allow analyzer version 23.

0.12.0+2

  • No user impacting changes. Tighten up a couple method signatures to specify that int is required.

0.12.0+1

  • Fixes bug with printing a percent or permille format with no fraction part and a number with no integer part. For example, print 0.12 with a format pattern of "#%". The test for whether there was a printable integer part tested the basic number, so it ignored the integer digits. This was introduced in 0.11.2 when we stopped multiplying the input number in the percent/permille case.

0.12.0

  • Make withLocale and defaultLocale use a zone, so async operations inside withLocale also get the correct locale. Bumping the version as this might be considered breaking, or at least behavior-changing.

0.11.12

  • Number formatting now accepts "int-like" inputs that don't have to conform to the num interface. In particular, you can now pass an Int64 from the fixnum package and format it. In addition, this no longer multiplies the result, so it won't lose precision on a few additional cases in JS.

0.11.11

  • Add a -no-embedded-plurals flag to reject plurals and genders that have either leading or trailing text around them. This follows the ICU recommendation that a plural or gender should contain the entire phrase/sentence, not just part of it.

0.11.10

  • Fix some style glitches with naming. The only publicly visible one is DateFormat.parseUtc, but the parseUTC variant is still retained for backward-compatibility.

  • Provide a better error message when generating translated versions and the name of a variable substitution in the message doesn't match the name in the translation.

0.11.9

  • Fix bug with per-mille parsing (only divided by 100, not 1000)

  • Support percent and per-mille formats with both positive and negative variations. Previously would throw an exception for too many modifiers.

0.11.8

  • Support NumberFormats with two different grouping sizes, e.g. 1,23,45,67,890

0.11.7

  • Moved petitparser into a regular dependency so pub run works.

  • Improved code layout of the package.

  • Added a DateFormat.parseStrict method that rejects DateTimes with invalid values and requires it to be the whole string.

0.11.6

  • Catch analyzer errors and do not generate messages for that file. Previously this would stop the message extraction on syntax errors and not give error messages as good as the compiler would produce. Just let the compiler do it.

0.11.5

  • Change to work with both petitparser 1.1.x and 1.2.x versions.

0.11.4

  • Broaden the pubspec constraints to allow current analyzer versions.

0.11.3

  • Add a --[no]-use-deferred-loading flag to generate_from_arb.dart and generally make the deferred loading of message libraries optional.

0.11.2

  • Missed canonicalization of locales in one place in message library generation.

  • Added a simple debug script for message_extraction_test.

0.11.1

  • Negative numbers were being parsed as positive.

0.11.0

  • Switch the message format from a custom JSON format to the ARB format ( https://code.google.com/p/arb/ )

0.10.0

  • Make message catalogs use deferred loading.

  • Update CLDR Data to version 25 for dates and numbers.

  • Update analyzer dependency to allow later versions.

  • Adds workaround for flakiness in DateTime creation, removes debugging code associated with that.

0.9.9

  • Add NumberFormat.parse()

  • Allow NumberFormat constructor to take an optional currency name/symbol, so you can format for a particular locale without it dictating the currency, and also supply the currency symbols which we don't have yet.

  • Canonicalize locales more consistently, avoiding a number of problems if you use a non-canonical form.

  • For locales whose length is longer than 6 change "-" to "_" in position 3 when canonicalizing. Previously anything of length > 6 was left completely alone.

0.9.8

  • Add a "meaning" optional parameter for Intl.message to distinguish between two messages with identical text.

  • Handle two different messages with the same text.

  • Allow complex string literals in arguments (e.g. multi-line)

1. Depend on it

Add this to your package's pubspec.yaml file:

dependencies:
  intl: "^0.15.1"

2. Install it

You can install packages from the command line:

$ pub get

Alternatively, your editor might support 'pub get'. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:intl/intl.dart';

About

Contains code to deal with internationalized/localized messages, date and number formatting and parsing, bi-directional text, and other internationalization issues.

Author

Email misc@dartlang.org Dart Team

Homepage

github.com/dart-lang/intl

Documentation

www.dartdocs.org/documentation/intl/0.15.1/

Source code (hyperlinked)

www.crossdart.info/p/intl/0.15.1/

Uploader

dgrove@google.com
alanknight@google.com
jmesserly@google.com
sigmund@google.com
nweiz@google.com
jacobr@google.com
keertip@google.com
kevmoo@google.com

Share