I wanted to make a simple calculator. I wanted to do it all in one function instead of defining functions separately for each operation, but I'm getting an error and I couldn't figure out why I was getting this error.
late num numberOne, numberTwo;
String result = '';
mathFunction(String text) {
if (textControllerTwo != '0') {
numberOne = num.tryParse(textControllerOne.text)!;
numberTwo = num.tryParse(textControllerTwo.text)!;
switch (text) {
case 'collection':
return result = (numberOne numberTwo).toString();
case 'interest':
return result = (numberOne - numberTwo).toString();
case 'multiply':
return result = (numberOne * numberTwo).toString();
case 'divided':
return result = (numberOne / numberTwo).toString();
}
} else {
return result = 'Number cannot be divided by 0';
}
setState(() {});
}
CodePudding user response:
It is better to get numberOne, numberTwo in methods and make them not optional or use the required annotaiton. make sure textControllerOne.text and textControllerTwo.text and text is not null.
CodePudding user response:
- Add
default
clause to yourswitch
statement. - Give a default value for each
num
value from tryParse. - Remove
setState(() {});
because you must not give aside effect
when calling your function/method. - No need to use a class/file scope variable (
numberOne
,numberTwo
,result
) for your function scope code. - Give a return type for your function/method.
here your simplified code:
// return a string result from mathFunction.
String mathFunction(String text) {
if (textControllerTwo != '0') {
// Give 0 if parse failed.
num numberOne = num.tryParse(textControllerOne.text)??0;
num numberTwo = num.tryParse(textControllerTwo.text)??0;
switch (text) {
case 'collection':
return (numberOne numberTwo).toString();
case 'interest':
return (numberOne - numberTwo).toString();
case 'multiply':
return (numberOne * numberTwo).toString();
case 'divided':
return (numberOne / numberTwo).toString();
default:
return "ERR";
}
} else {
return 'Number cannot be divided by 0';
}
}