How to allow a null return from a function in dart with null safety on

Issue

After moving to null safety I am having hard time on how to refactor some pieces of my code.

I have a method looking like this

final Reducer<Exception> _errorReducer = combineReducers<Exception>([
  TypedReducer<Exception, ErrorOccurredAction>(_errorOccurredReducer),
  TypedReducer<Exception, ErrorHandledAction>(_errorHandledReducer),
]);

Exception _errorOccurredReducer(Exception _, ErrorOccurredAction action) {
  return action.exception;
}

Exception _errorHandledReducer(Exception _, ErrorHandledAction action) {
  return null;
}

since error is initialized to null, how can I allow a null return to be able to set it back to null.

got recently introduced to statically typed workflow so I am learning.

note: if there is a better practice to handle what I am trying to achieve do mind to share that to.

Solution

Simply add a ? after the type if the variable accepts null.


Exception? _errorOccurredReducer(Exception _, ErrorOccurredAction action) {
  return action.exception;
}

Exception? _errorHandledReducer(Exception _, ErrorHandledAction action) {
  return null;
}

Answered By – Alexandre Ardhuin

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *