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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With