How to build Null Factory Constructors with Null Safety?

Issue

A common Dart pattern before null safety for creating static method holder classes was the following:

class MyMethodScope {
  /// Prevents instantiation of this class.
  factory MyMethodScope._() => null;

  static void noop() {}
}

This is not possible with null safety because the return type of a factory constructor is not nullable apparently.

Solution

Based on https://github.com/dart-lang/language/issues/604, it looks expected that factory constructors can no longer return null, so you can’t do it.

You alternatively could just use a private constructor (whether factory or not) that returns a non-null object. That would still prevent the class from being instantiated outside of the library. (Of course, it wouldn’t prevent the class from being instantiated within the library, but you could just avoid doing that since you control your own library. You could move the class into a separate library if you’re still concerned about accidental instantiation.)

Or just declare the class as abstract, which is the normal and direct way to prevent a class from being instantiated.

Besides, Effective Dart says to avoid such classes.

Answered By – jamesdlin

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

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