JULIUS
JULIUS

Reputation: 121

The method '+' was called on null. Receiver: null Tried calling: +(123)

I get this error and I don't know why. I basically just check the operator and make calculations based on that.

Thank you for your help.

Function:


  void calculate() {
    setState(() {
      int num1int = int.tryParse(_num1);
      int num2int = int.tryParse(_num2);
      int result = 0;
      if (_operator == "+") {
        result = num1int + num2int;
      }
      else if (_operator == "-") {
        result = num1int - num2int;
      }
      else if (_operator == "*") {
        result = num1int * num2int;
      }
      else if (_operator == "/") {
        result = num1int ~/ num2int;
      }
    });
  }

Upvotes: 0

Views: 243

Answers (2)

Sajjad
Sajjad

Reputation: 3228

please change your code to

  if (_operator == "+") {
    result = num1int??0 + num2int??0;
  }
  else if (_operator == "-") {
    result = num1int??0 - num2int??0;
  }
  else if (_operator == "*") {
    result = num1int??1 * num2int??1;
  }
  else if (_operator == "/") {
    result = num1int??1 ~/ num2int??1;
  }

Upvotes: 1

Toby
Toby

Reputation: 316

if "int.tryParse" can not convert it into integer, it will be returning "null". So your code does: null + null. You can add a check for num1int and num2int if it is null before calcultion.

Upvotes: 1

Related Questions