Logic
Logic

Reputation: 63

Problem concerning null safety in functions

I have this function called add which adds two numbers and returns the result in dart.

void main() {
  int step1Result = add(n1: 5, n2: 9);
  int step2Result = multiply(step1Result, 5);
  double finalResult = step2Result / 3;
  print(finalResult);
}

int add({int n1, int n2}){
  return n1 + n2;
}

but it keeps on throwing the error that n1 and n2 can't have a value of 'null' because of its type, but the implicit default value is 'null'. I tried adding the ? mark but the it threw another error saying

The operator '+' can't be unconditionally invoked because the receiver can be 'null'.

Upvotes: 0

Views: 170

Answers (1)

BLKKKBVSIK
BLKKKBVSIK

Reputation: 3576

The error comes from the declaration of your add function: Here

int add({int n1, int n2}){
    // ...
}

Here you're declaring two optional parameters to the functions. But n1 and n2 are int and not int?

To fix this issue, you can either transform your function to take int? types. Or to add the required keyword to tell that the function will only work if both parameters will be given.

void main() {
    int step1Result = add(n1: 5, n2: 9);
    int step2Result = multiply(step1Result, 5);
    double finalResult = step2Result / 3;
    print(finalResult);
}

int add({required int n1,required int n2}){
    return n1 + n2;
}

You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.

https://api.flutter.dev/flutter/material/DropdownButton-class.html.

Upvotes: 1

Related Questions