Sub topic 9
Plural and select messages
This chapter assumes you know basic Dart, null safety, MaterialApp, ARB files, and the gen-l10n workflow. It focuses on ICU message syntax for choosing text based on a number or a string.
Choose plural text from a number
A plural message has this shape:
{count, plural, =0{No trips} =1{One trip} other{{count} trips}}The first value, count, is the placeholder. plural tells Flutter to choose a branch based on that number. Each branch has a selector and text.
=0matches exactly zero.=1matches exactly one.otheris the required fallback for all remaining values.{count}inside a branch prints the number.
Locale rules can have categories such as one, few, and many. For example, a language may use different grammar for several counting ranges. Exact selectors such as =0 are checked before category selectors.
Add the message and its metadata to the template ARB file:
{
"@@locale": "en",
"tripCount": "{count, plural, =0{No trips} =1{One trip} other{{count} trips}}",
"@tripCount": {
"description": "Number of trips planned by the user",
"placeholders": {
"count": {
"type": "int"
}
}
}
}A Spanish translation can use different wording while keeping the same key and placeholder:
{
"@@locale": "es",
"tripCount": "{count, plural, =0{Sin viajes} =1{1 viaje} other{{count} viajes}}"
}The generated Dart method accepts an int:
final l10n = AppLocalizations.of(context)!;
Column(
children: [
Text(l10n.tripCount(0)),
Text(l10n.tripCount(1)),
Text(l10n.tripCount(4)),
],
)The translation, rather than Dart code, owns the sentence structure. This matters because word order and plural rules differ between languages.
Choose text with a select message
A select message chooses a branch from a string value. It is useful for stable categories such as account roles, not for arbitrary user input.
{
"@@locale": "en",
"roleLabel": "{role, select, admin{Administrator} editor{Editor} other{Viewer}}",
"@roleLabel": {
"description": "Label for the current account role",
"placeholders": {
"role": {
"type": "String",
"example": "editor"
}
}
}
}The selector must match exactly. If it is admin, the result is Administrator. If it is editor, the result is Editor. Every other value uses other.
Text(l10n.roleLabel(user.role))select does not understand grammatical gender or plural rules by itself. It simply compares the supplied string with the listed cases.
Combine selectors carefully
Messages can nest selectors. For example, a message can select a role and then apply plural rules to a count. Keep nested messages short and test every branch. Complex sentences are often easier to translate as separate messages.
Exercise
Exercise
What output does roleLabel('guest') produce when the message has admin, editor, and other{Viewer} branches?
Show answer
It produces Viewer, because guest matches neither named case and therefore uses other.