how to check if variable is null in dart?

Issue

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);
 }

Solution

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);
}

Answered By – Alexandre Ardhuin

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.