Home > Net >  Null check operator used on a null value when creating an instance
Null check operator used on a null value when creating an instance

Time:09-30

I defined a simple class, it contains a nullable member variable, we can assign it by pass a reference from outside in constructor. when I try to run it, runtime throw 'Null check operator used on a null value' error. Do you know why? Here is my code:

abstract class MyClassCallback {
    void onFinish();
}

class MyClass {
    MyClassCallback? _callback;

    MyClass(MyClassCallback? callback) : _callback = callback!;
}

void main() {
   var o = new MyClass(null);
   // Null check operator used on a null value
}

CodePudding user response:

I think this is happening because your are using Not Null ! operator.

Just define MyClass in following way

class MyClass {
    MyClassCallback? _callback;

    MyClass(MyClassCallback? callback) : _callback = callback; // ! removed
}

CodePudding user response:

In your code you are passing a null value to constructor but in this

MyClass(MyClassCallback? callback) : _callback = callback!;

line you are saying that ok assign the callback! value to _callback and because of that ! you are implying that callback is not null which is not true since you’ve passed null to it from the main function, so remove it and everything’s will be fine.

  • Related