I would check if the int is greater than 1 and make the word plural or singular. I mean something like the following example:
If the apple
variable is 1, it will return:
1 apple
Else:
2 apples
Here's the code of how I do this so far:
"$totalApples ${totalApples > 1 ? "apples" : "apple"}"
But, I think there should be some function or package or other way to solve this problem, right? I wish to use a short code instead of this long code.
How to check if int is greater than 1 and make word plural or singular? I would appreciate any help. Thank you in advance!
CodePudding user response:
yes, there is a plural
method in the intl
package, check it from here.
the Getx
package provide same functionality with a plural
method.
However, if you want just to make a simple-call method to get the plural, you can use Dart extension methods, like this:
extension PluralExtension on int {
String plural(String singularWord, [String pluralLetters = "s"]) {
return this > 1 ? "$this $singularWord$pluralLetters" : "$this $singularWord";
}
}
print(5.plural("apple")); // 5 apples
print(0.plural("apple")); // 0 apple
print(1.plural("apple")); // 1 apple
print(10.plural("tomato", "es")); // 1 tomatoes
print(1.plural("tomato", "es")); // 1 tomato
In this example, I added the a custom plural
method on the int
type, so you can call it simply on anything that's a int
.