Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if int is greater than 1 and make word plural or singular in Flutter?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading