Home > OS >  I get an error 'unexcepted null value' (Flutter)
I get an error 'unexcepted null value' (Flutter)

Time:12-04

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:

  1. Add default clause to your switch statement.
  2. Give a default value for each num value from tryParse.
  3. Remove setState(() {}); because you must not give a side effect when calling your function/method.
  4. No need to use a class/file scope variable (numberOne, numberTwo, result) for your function scope code.
  5. 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';
    }
  }
  • Related