Home > Software design >  how to check if variable is null in dart?
how to check if variable is null in dart?

Time:03-19

I am new to dart. I want to do something like this. But editor says it is 'unnecessary_null_comparison'. What is the best way in dart to do something like this?

 EventType? et = dbHandler.getEventType(widget.eventName) as EventType;
 if (et != null) {
   dbHandler.insertEventType(eventType);
 }

CodePudding user response:

If dbHandler.getEventType(widget.eventName) returns a nullable value you should use as EventType?. Then your code should work as expected.

EventType? et = dbHandler.getEventType(widget.eventName) as EventType?;
if (et != null) {
  dbHandler.insertEventType(et);
}

CodePudding user response:

Dart has sound null safety so when you casted it to EventType using as EventType, it is not nullable by definition, that's why it's saying the null comparison is unnecessary because it'll always evaluate to true.

  • Related