Sub topic 9
Plural and select messages
This chapter assumes you have a working gen-l10n setup: flutter_localizations in pubspec.yaml, an l10n.yaml, a template app_en.arb, and AppLocalizations wired into MaterialApp. It also assumes you know how placeholders are declared in ARB metadata.
Why plain string interpolation fails
A naive approach builds sentences in Dart:
Text('$count ${count == 1 ? 'trip' : 'trips'}')This breaks in two ways. The grammar lives in code, so translators cannot change it. And many languages do not split into "one" and "not one". Russian uses different word forms for 1, 2 to 4, and 5 to 20. Arabic has six forms.
ARB files solve this with ICU message syntax. The whole sentence, including its grammatical variants, lives in one translatable string. gen-l10n turns it into a Dart method that picks the right branch at runtime.
Plural messages
A plural message has the form {placeholder, plural, selector{text} ...}. The template file from earlier chapters already contains one:
{
"tripCount": "{count, plural, =0{No trips} =1{1 trip} other{{count} trips}}",
"@tripCount": {
"description": "Number of trips the user has planned",
"placeholders": {
"count": {
"type": "int"
}
}
}
}Here is how the message breaks down:
countis the placeholder that drives the choice. Declare it asintornumin the metadata.=0and=1are exact matches. They compare the value directly.otheris the fallback. It is required in every plural message.{count}inside a branch inserts the number into the text. Branches can contain any text and other placeholders.
The generated method is l10n.tripCount(int count), and a String argument is a compile-time error.
Exact matches and categories
Besides =N selectors, ICU defines six plural categories: zero, one, two, few, many, and other. Each language's rules decide which numbers fall into which category. Those rules come from the Unicode CLDR data that the intl package embeds.
| Language | Categories it uses | Example |
|---|---|---|
| English | one, other | 1 is `one`; 0, 2, 11 are `other` |
| Spanish | one, many, other | 1 is `one`; 1,000,000 is `many`; 2 is `other` |
| Russian | one, few, many, other | 1 and 21 are `one`; 2 to 4 and 22 are `few`; 0, 5 to 20, and 25 are `many` |
| Arabic | zero, one, two, few, many, other | 0 is `zero`; 2 is `two`; 3 to 10 is `few` |
| Japanese | other | every number is `other` |
Exact matches win over categories. If a message has =1{...} and one{...}, the value 1 uses =1. This is why English messages often use =0 for "No trips". English has no zero category, so zero{...} would never be chosen in English.
A Russian translation
Translators add the categories their language needs. Create lib/l10n/app_ru.arb:
{
"@@locale": "ru",
"appTitle": "Планировщик поездок",
"greeting": "Привет, {name}!",
"tripCount": "{count, plural, =0{Нет поездок} one{{count} поездка} few{{count} поездки} many{{count} поездок} other{{count} поездки}}",
"departure": "Отправление: {date}"
}The template only has other, but the Russian file uses all of one, few, many, and other. Only the template file needs the metadata, so the translated file does not repeat it.
Select messages
A select message chooses a branch by matching a string. The syntax is {placeholder, select, value{text} ... other{text}}. Use it for grammatical gender, roles, or any small set of named cases.
{
"inviteMessage": "{host, select, female{She invited you to a trip} male{He invited you to a trip} other{They invited you to a trip}}",
"@inviteMessage": {
"description": "Shown when another user invites the current user. The host value is the inviter's grammatical gender.",
"placeholders": {
"host": {
"type": "String"
}
}
}
}The generated method takes a String: l10n.inviteMessage('female').
Matching is exact and case-sensitive. 'Female', 'f', or an empty string all fall through to other. That fallback makes typos silent, so keep the strings out of scattered call sites. A common pattern is to map an enum to the string in one place:
enum Gender { female, male, unspecified }
String inviteText(AppLocalizations l10n, Gender host) {
final key = switch (host) {
Gender.female => 'female',
Gender.male => 'male',
Gender.unspecified => 'other',
};
return l10n.inviteMessage(key);
}Select values must be plain words. They can be any string your code agrees on, such as admin or editor. They are not categories defined by ICU.
Combining placeholders, plurals, and selects
A branch may contain ordinary placeholders, so a message can mix them. Declare each placeholder in the metadata with its type. The plural driver is int or num, the select driver is String, and the others use their own types.
The order of parameters in the generated method follows the metadata. When a message has several placeholders, open the generated app_localizations.dart and check the signature before you write call sites.
You can also nest a plural inside a select branch. Doing so is legal ICU, but each combination of branches becomes a separate string for translators to review. Often it is simpler to split the sentence into two messages.
Using the messages in widgets
Calling these messages looks the same as calling any other generated method. This screen shows a plural and a select together:
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';
class InviteScreen extends StatelessWidget {
const InviteScreen({super.key, required this.trips, required this.host});
final int trips;
final String host;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(title: Text(l10n.appTitle)),
body: Column(
children: [
Text(l10n.inviteMessage(host)),
Text(l10n.tripCount(trips)),
],
),
);
}
}Formatting the number inside a plural
The {count} in other{{count} trips} prints the integer as is, so 1200 appears as 1200. To format it for the locale, add a format to the placeholder:
"@tripCount": {
"description": "Number of trips the user has planned",
"placeholders": {
"count": {
"type": "int",
"format": "decimalPattern"
}
}
}The text then reads 1,200 trips in English and 1.200 viajes in Spanish. The plural category is still chosen from the number, not from the formatted text.
Testing plurals in several languages
Plural bugs usually appear on specific numbers, so test the boundaries of each category. This test uses the Russian file above:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/l10n/app_localizations.dart';
Future<void> pumpTripCount(WidgetTester tester, int count) async {
await tester.pumpWidget(
MaterialApp(
locale: const Locale('ru'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) =>
Text(AppLocalizations.of(context)!.tripCount(count)),
),
),
);
await tester.pumpAndSettle();
}
void main() {
const expected = {
0: 'Нет поездок',
1: '1 поездка',
2: '2 поездки',
5: '5 поездок',
21: '21 поездка',
22: '22 поездки',
};
expected.forEach((count, text) {
testWidgets('Russian plural for $count', (tester) async {
await pumpTripCount(tester, count);
expect(find.text(text), findsOneWidget);
});
});
}Replace my_app with the package name from your pubspec.yaml.
Common errors
- Missing
other. Generation fails. Add the branch to the message that is named in the error. - Wrong placeholder type. A plural driven by a
Stringplaceholder, or a select driven by anint, produces a generation error or a bad signature. Plurals takeintornum, and selects takeString. - Unbalanced braces. Every branch needs its own
{...}, and the whole message needs matching outer braces. An error likeUnexpected tokenusually points here. - Apostrophes. A single quote can be read as an escape character in ICU syntax. If a translation such as
l'amiloses text, setuse-escaping: trueinl10n.yamland write literal quotes as doubled'', then regenerate. - Using
zerofor English. English has nozerocategory, so use=0. - Hard-coded plural words in Dart. If code adds an "s" or picks between two messages by hand, it undoes the point of this chapter. Pass the number to the message instead.
Exercise
Your Polish translator reports that "5 trips" and "2 trips" need different word forms. The template has only =1{1 trip} and other{{count} trips}. What do you change, and where? What happens to Polish if the other branch is removed?
Show answer
Nothing changes in the template, because English only needs one/other forms. In app_pl.arb, the translator writes the tripCount message with the categories Polish uses (one, few, many, and other), and keeps {count} inside each branch. Only the template carries the metadata. If other is removed, gen-l10n fails with a parse error, because other is required in every plural message.
Exercise
A call l10n.inviteMessage('Female') returns "They invited you to a trip" even though the user is female. Why, and how do you prevent it?
Show answer
Select matching is exact and case-sensitive, so 'Female' does not match the female branch and falls through to other. Prevent it by mapping an enum to the exact strings in one helper, such as inviteText, instead of passing free-form strings from many call sites.