Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build Null Factory Constructors with Null Safety?

Tags:

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.

like image 433
creativecreatorormaybenot Avatar asked Jun 23 '20 22:06

creativecreatorormaybenot


1 Answers

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.

like image 175
jamesdlin Avatar answered Nov 09 '22 23:11

jamesdlin