Manage Plural / gender in localization on flutter using json

5.3k Views Asked by At

I'm developing a mobile application using flutter / dart. The app needs to be localized using JSON files.

I need to handle the plural / gender in strings. Actually i'm using sprintf library, with some placeholder in the JSON code like:

{
  ...
   "vehiclelabelKmTraveledReadable": "In %s Km",
  ...
}

so I replaced the '%s' placeholder with a variable value.

The problem is how to handle plurals, like

{
"vehiclePeriod": "Every %s month(s?)"
}

But if %s is 1, it's wrong. Does anybody knows how to manage this kind of cases?

2

There are 2 best solutions below

1
Slah Layouni On

I managed this kind of case using intl package from flutter, but it uses .arb files instead of .json.

Here an example how to handle it with intl package

Intl.plural(howMany,
      zero: "$howMany An",
      one: "$howMany An",
      other: "$howMany Ans",
      name: 'dogYearsOld',
      locale: localeName,
      args: [howMany]);

Hope this can help you get started.

0
Ec7ipse On

I like to use this plugin for localization. It's really easy to use. And it supports many formats as well as JSON. Also it supports plurals. It's better to read docs, but small code snippet here

ru.json

{
  "day": {
    "zero":"{} дней",
    "one": "{} день",
    "two": "{} дня",
    "few": "{} дня",
    "many": "{} дней",
    "other": "{} дней"
  },
}

main.dart

print('day'.plural(21));