如何防止整数值变为负值

How can I prevent integer value from going negative

我在一个应用程序中工作,在该应用程序中,我可以选择为所选产品选择数量,默认情况下数量设置为 1,同时增加和减少数量我可以使用负数,例如 -1 、-2、 -3... 如何限制数量变为负值。

这是我减少数量价值的代码

setState(() {
  itemCount = itemCount - 1;
  price = itemCount - price;
});

您可以像@Mobina 所说的那样进行 if 检查:

if (itemCount > 0) price = itemCount - price;

或者使用数学库中的max函数:

import 'dart:math';

void main() {
  final itemCount = 1;
  final price = max(0, itemCount - 5);
}