Antony David
Antony David

Reputation: 87

How can I prevent integer value from going negative

I am working in an app in which I have option to choose quantity number for selected product by default quantity is set to 1 while increasing and decreasing quantity I am able to go to negative numbers like -1 ,-2,-3... How do I restrict quantity from going negative.

this my code for reducing quantity value

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

Upvotes: 0

Views: 1718

Answers (1)

HBS
HBS

Reputation: 670

You can do an if check as @Mobina said:

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

Or use the max function from the math library:

import 'dart:math';

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

Upvotes: 2

Related Questions