• This repository has been archived on 31/Aug/2023
  • Stars
    star
    527
  • Rank 80,880 (Top 2 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Internationalization and localization support

This repository has been moved to https://github.com/dart-lang/i18n/tree/main/pkgs/intl. Please file any PRs and issues there.


Dart CI Pub

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 = DateFormat.yMd('ar');
var dateString = format.format(DateTime.now());

or

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

or

Intl.defaultLocale = 'es';
DateFormat.jm().format(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 must match the name (or ClassName_methodName) and arguments list of the function respectively. For messages without parameters, both of these can be omitted.

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 $howMany 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 $howMany 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 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. See ARB. 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 = NumberFormat('###.0#', 'en_US');
print(f.format(12.345));
  ==> 12.35

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.

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.

DateFormat.yMMMMEEEEd().format(aDateTime);
  ==> 'Wednesday, January 10, 2012'
DateFormat('EEEEE', 'en_US').format(aDateTime);
  ==> 'Wednesday'
DateFormat('EEEEE', 'ln').format(aDateTime);
  ==> 'mokΙ”lΙ” mwa mΓ­sΓ‘to'

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

DateFormat.yMd('en_US').parse('1/10/2012');
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.

DateFormat.yMEd().add_jms().format(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.

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

More Repositories

1

angular.dart

Legacy source repository. See github.com/dart-lang/angular
1,250
star
2

stagehand

Dart project generator - web apps, console apps, servers, and more.
Dart
660
star
3

dart-samples

Various samples and examples in Dart
Dart
468
star
4

sdk

The Dartino project was an experiment seeking to improve productivity when writing application code for embedded devices.
Dart
325
star
5

dart-services

The server backend for a web based interactive Dart service
Dart
312
star
6

angular.dart.tutorial

AngularDart tutorial
Dart
236
star
7

pub_server

Reusable components for making a pub package server
Dart
215
star
8

bleeding_edge-DEPRECATED-USE-SDK-INSTEAD

NO LONGER SYNCING. use dart-lang/sdk
Dart
210
star
9

www.dartlang.org

DEPRECATED - OLD SITE for DART
HTML
197
star
10

dart-tutorials-samples

Sample code for "A Game of Darts" tutorial
Dart
187
star
11

polymer-dart

Polymer support for Dart
Dart
181
star
12

ts2dart

ts2dart TypeScript to Dart transpiler
TypeScript
177
star
13

js_facade_gen

Generates package:js Javascript interop facades for arbitrary TypeScript libraries
TypeScript
159
star
14

dev_compiler

DEPRECATED - Moved to main SDK
JavaScript
136
star
15

intl_translation

Message extraction and code generation from translated messages for the intl package
Dart
128
star
16

tflite_native

A Dart interface to TensorFlow Lite (tflite) through dart:ffi
Dart
125
star
17

rpc

RPC package for building server-side RESTful Dart APIs.
Dart
117
star
18

js-interop-deprecated

Deprecated: code is now in the SDK repo
Dart
114
star
19

one-hour-codelab

Learn how to build a webapp with Dart in one hour.
Dart
104
star
20

dart-up-and-running-book

ARCHIVE - The DocBook (XML) and code that make up the O'Reilly book Dart: Up and Running
Dart
98
star
21

isolate

Makes working with Dart isolates easier.
Dart
90
star
22

dart_docker

Docker images for Dart
Shell
85
star
23

dart_enhancement_proposals

This repo contains info on DEP - Dart Enhancement Proposal
Dart
81
star
24

dart-protoc-plugin

Dart plugin for protobuf compiler (protoc)
79
star
25

discoveryapis_generator

Create API Client libraries based on the API's Discovery documentation
Dart
77
star
26

graphs

Graph algorithms
Dart
74
star
27

angular_analyzer_plugin

WORK MOVED TO dart-lang/angular repository
69
star
28

di.dart

DEPRECATED
Dart
66
star
29

googleapis_examples

Examples for accessing Google APIs with Dart
Dart
66
star
30

angular_components_example

A sample usage of https://github.com/dart-lang/angular_components
Dart
66
star
31

polymer-dart-patterns

Small, useful, snippets/samples that show how to do things the Polymer.dart way.
HTML
63
star
32

conference_app

Dart
56
star
33

paper-elements

Polymer.dart <=0.17.0 wrappers for Polymer's paper-elements
HTML
52
star
34

pub-dartlang

DEPRECATED - old pub.dartlang.org site in Python
Python
43
star
35

dump-info-visualizer

A visualizer for the JSON data produced by the dart2js --dump-info command
Dart
43
star
36

googleapis_auth

Obtain OAuth 2.0 credentials to access Google APIs
Dart
38
star
37

http_server

Utility classes for HTTP server
Dart
37
star
38

bazel

Bazel support for Dart projects [EXPERIMENTAL]
Dart
34
star
39

appengine_samples

Dart App Engine samples
Dart
33
star
40

core-elements

Polymer core-* elements wrapped or ported for Dart
HTML
33
star
41

route.dart

MOVE to https://github.com/dart-lang/angular/tree/master/angular_router
Dart
29
star
42

ton80

A benchmark suite for Dart
Dart
25
star
43

polymer_elements

JavaScript
24
star
44

shelf_static

archived repo
Dart
24
star
45

shelf_proxy

A shelf handler for proxying requests to another server.
Dart
23
star
46

dartdoc-viewer

deprecated. Use dartdoc instead.
Dart
23
star
47

sample-todomvc-polymer

todomvc example built with polymer.dart
Dart
22
star
48

shelf_web_socket

A WebSocket handler for Shelf.
Dart
22
star
49

kernel

Dart IR (Intermediate Representation) -- moved to dart-lang/sdk
Dart
21
star
50

web-components

Dart package providing the web components platform polyfills
JavaScript
18
star
51

polymer-core-and-paper-examples

This repo contains examples for the core and paper polymer elements, from Dart
HTML
16
star
52

resource

Resource loading library.
Dart
16
star
53

http_io

Dart
15
star
54

http_retry

HTTP client middleware that automatically retries requests
Dart
15
star
55

angular_ast

DEPRECATED - development moved to share angular repo
Dart
15
star
56

dart2js_info

Model of the data produced by dart2js with --dump-info, and tools that process the information.
Dart
14
star
57

polymer-and-dart-codelab

Polymer Dart codelab sample code
HTML
14
star
58

custom-element-apigen

Tool to generate Dart APIs for polymer custom elements written in Javascript
Dart
13
star
59

old_ghpages_server_docs

Documentation for Dart on the server
HTML
13
star
60

observe

Support for marking objects as observable, and getting notifications when those objects are mutated
Dart
13
star
61

angular_test

**MOVED**: Repository has moved to https://github.com/dart-lang/angular
13
star
62

vm_service_client

A Darty client for the VM service protocol
Dart
12
star
63

smoke

Smoke is a Dart package that exposes a reduced reflective system API. This API includes accessing objects in a dynamic fashion (read properties, write properties, and call methods), inspecting types (for example, whether a method exists), and symbol/string convention.
Dart
12
star
64

rules_dart

Dart rules for Bazel
Python
11
star
65

polymer-spa-example

A sample "Single Page App" for Polymer.dart <=0.17.0
Dart
11
star
66

vm_service_drivers

[DEPRECATED] Libraries to access the Dart VM Service Protocol
Dart
11
star
67

barback

An asset build system for Dart.
Dart
11
star
68

angulardart.org

Website for AngularDart, a web framework for Dart
HTML
10
star
69

utf

Provides common operations for manipulating Unicode sequences
Dart
10
star
70

rpc-examples

Dart
9
star
71

expected_output

Dart
9
star
72

memcache

Memcache interface for the Dart appengine package
Dart
9
star
73

atom-dartino

Atom Plug-in for Dartino
JavaScript
8
star
74

angular2_api_examples

DEPRECATED - content moved
8
star
75

shelf_rpc

shelf_rpc is a Shelf Handler for the Dart rpc package.
Dart
7
star
76

webcore

Web DOM IDL files and support files copied from Blink
Python
7
star
77

eclipse3

DEPRECATED - NO LONGER maintained/supported - Eclipse plugins and Dart Editor
Java
7
star
78

package_resolver

First-class package resolution strategy classes.
Dart
7
star
79

polymer_interop

Repackaging of the original polymer js source.
HTML
7
star
80

dart2_fix

A tool to migrate API usage to Dart 2
Dart
7
star
81

plugin

Dart
7
star
82

observatory

The website for Dart VM's Observatory
CSS
7
star
83

initialize

Provides a common interface for initialization annotations on top level methods, classes, and libraries in Dart
Dart
7
star
84

dart2es6

Dart to ECMAScript 6 transpiler
JavaScript
6
star
85

dart-doc-syncer

A utility for syncing Dart examples for the public docs
Dart
6
star
86

http_throttle

HTTP client middleware that throttles requests.
Dart
6
star
87

io_2017_components_codelab

Dart
6
star
88

code_transformers

Package to help with code transformers in barback
Dart
5
star
89

discoveryapis_commons

A package used by client libraries generated from discovery documents.
Dart
5
star
90

shelf_test_handler

A Shelf handler that makes it easy to test HTTP interactions
Dart
5
star
91

shelf_appengine

A set helpers to make it easy to use Shelf on App Engine.
Dart
5
star
92

csslib-test-suite

Suite of CSS tests (originating from the W3C) used to validate CSS parsing.
HTML
4
star
93

site-events

Source of events.dartlang.org
CSS
3
star
94

test_reflectable

tests for the reflectable package
Dart
3
star
95

shelf_packages_handler

A shelf handler for serving a `packages/` directory
Dart
3
star
96

polymer-expressions

Polymer.dart <=0.17.0 support for polymer expressions in Dart
Dart
3
star
97

gulp-ts2dart

Gulp task to transpile TypeScript code to Dart
JavaScript
3
star
98

func

Repository for the func package containing convenience typedefs for specifying function types.
Dart
3
star
99

scheduled_test

A package for writing readable tests of asynchronous behavior.
Dart
3
star
100

multi_server_socket

An implementation of dart:io's ServerSocket that wraps multiple servers and forwards methods to all of them
Dart
3
star