Home > Software design >  Return Future<void> from a sync function in Dart
Return Future<void> from a sync function in Dart

Time:12-17

I have a function to override and I want it to do nothing. The base class function is abstract. I have two options for implementation:

// option 1
@override
Future<void> cancelReadStream() async {}

// option 2
@override
Future<void> cancelReadStream() {
  return Future.value();
}

Dart code metrics tells me to avoid redundant async, so I thought it is best to return a Future<void>. Is Future.value() the best way to return a Future<void>?

CodePudding user response:

I would go with option 1, it's just the most solid implementation. Dart metrics can be a little invasive sometimes, I would just ignore it. Once you actually write any async code the warning will disappear anyway.

CodePudding user response:

I'd argue that the code metrics are wrong.

It's exactly the third item they list:

  • A value is returned and it will be impliclty wrapped in a future. async is shorter than Future.value(...).

In this case the value is null, and it's returned implicitly, but it's still shorter than Future<void>.value(null);

The code

@override
Future<void> cancelReadStream() async {}

is perfectly reasonable and readable. It's an asynchronous function (returns a future), which does nothing before completing that future.

I'd consider reporting it to the DCM team, as a false positive.

  • Related