im making a small calculator app with flutter i want to add a validator to check when the second number entered is zero to avoid when dividing by zero
when the user clicks divide button it should check if it was so i dont know how to put that so i need some help
this is my code
TextButton.icon(
icon: Icon(Icons.safety_divider),
label: Text('Divide'),
onPressed: () {
setState(() {
double result = double.parse(num1controller.text) /
double.parse(num2controller.text);
resulttext = result.toStringAsPrecision(3);
});
CodePudding user response:
Here is what I came up with:
onPressed: () {
double num1 = double.parse(num1controller.text);
double num2 = double.parse(num2controller.text);
if (num2 == 0) {
// do something here
num2 = 1;
}
double result = num1 / num2; // I recommend you put as few code as possible on `setState`
setState(() {
resulttext = result.toStringAsPrecision(3);
});
}