Plurals in Dart Example
Sometimes in our app we have to change sentences to plurals depends upon number of quantity, for example a food delivery app shows text like this:
- if user add 1 food item, shows
1 ITEM
- if user add second food item, shows
2 ITEMS
- If no items added,
EMPTY CART
You can use Plurals in your Dart string by using intl
package. It is also used for internationalization and localization and date/number formatting .
- Add dependency:
dependencies: intl: ^0.16.0
- Import package
import 'package:intl/intl.dart' as intl;
- Usage
String showCartMessage(int quantity) { return Intl.plural( quantity, zero: 'EMPTY CART', one: '$quantity ITEM', other: '$quantity ITEMS', name: "ITEM", args: [quantity], examples: const {'quantity': 4}, desc: "Food quantity to order from cart", ); }
Pass your value in showCartMessage()
and it will return a String
text to show
- Output
You can check the code at my GitHub Repo