Sobes.tech
Middle

What is the Never type in Dart language?

sobes.tech AI

Answer from AI

The Never type is an indicator that an expression will never successfully complete. It is used for functions and methods that either throw an exception or enter an infinite loop.

Examples of usage:

  • Function that throws an exception:

    Never _throwError(String message) {
      // Throws an exception, the function never returns a value
      throw StateError(message);
    }
    
  • Function with an infinite loop:

    Never _infiniteLoop() {
      // Enters an infinite loop, the function never terminates
      while (true) {
        // Do something
      }
    }
    

The main advantage of Never is that it helps the compiler understand that code after such a function or method call is unreachable, allowing static analysis to catch potential errors such as unreachable code and improper error handling.

Unlike void, which means that a function does not return a value (but completes successfully), Never means that the function will never complete in principle.

// Function returning void (completes successfully, but without a value)
void doSomething() {
  print('Doing something');
}

// Function returning Never (never completes successfully)
Never crashAndBurn() {
  throw 'Oh no!';
}

The Never type is the bottom type, meaning it is a subtype of any other type. This allows a function returning Never to be used in places where any other type is expected.