avoid-returning-null-for-void

Same as avoid_returning_null_for_void in Dart lints

Path
lint/suspicious/avoid-returning-null-for-void
Default
On (recommended)
Origin
Dart lints
Rule
131 of 512
recommended

Flags return null; (and => null bodies) in synchronous void functions and asynchronous Future<void> functions. A nullable future permits a null result only in a synchronous body; void async is exempt.

Returning an explicit null from a void function is contradictory: the signature promises no value, so the null is dead and usually reflects confusion about the function's contract or a copy-paste from a nullable one. Drop the value and write a bare return;, or change the return type if the function is really meant to produce a value. Each nested function is judged by its own return type, so an inner closure is not tainted by an enclosing void frame.

Invalid

example.dartdart
void f() {
  return null;
}

void g() => null;

Future<void> h() async {
  return null;
}

class C {
  void method() {
    return null;
  }

  set value(int v) {
    return null;
  }
}

void outer() {
  void inner() {
    return null;
  }

  inner();
}
Don't return `null` from a function with a `void` return type.
1void f() {
2 return null;
Don't return `null` from a function with a `void` return type.
4
5void g() => null;
Don't return `null` from a function with a `void` return type.
7Future<void> h() async {
8 return null;
Don't return `null` from a function with a `void` return type.
12 void method() {
13 return null;
Don't return `null` from a function with a `void` return type.
16 set value(int v) {
17 return null;
Don't return `null` from a function with a `void` return type.
22 void inner() {
23 return null;

Valid

example.dartdart
void f() {
  return;
}

int g() {
  return null;
}

int? h() => null;

Future<void> i() async {
  await Future<void>.value();
}

class C {
  int _v = 0;

  void method() {
    print('no return');
  }

  int compute() => null;

  set value(int v) {
    _v = v;
  }
}

void outer() {
  int inner() {
    return null;
  }

  inner();
}

void parenthesizedReturn() {
  return (null);
}

void parenthesizedArrow() => (null);

Configure avoid-returning-null-for-void

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "suspicious": {
        "avoid-returning-null-for-void": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/suspicious/avoid-returning-null-for-void: <reason>