If you have a Dart class that only contains static methods and constants, most likely you want to make the class to be non-instantiable. However, even if you don't provide any constructor, Dart creates an empty constructor for the class by default.
Creating Private Constructor to Prevent Instantiation
The solution is creating a private constructor. By declaring a private constructor, Flutter no longer creates the default constructor. To make the constructor private, you need to use _
(underscore) which means private. The example below creates a class named MyUtils
with a private constructor as the only constructor.
class MyUtils {
MyUtils._();
static void printMessage() {
print('Woolha.com');
}
}
Calling the Constructor From Another File
If you try to call the default constructor from another file, you will get an error because the constructor is private.
// The class MyUtils doesn't have a default constructor
MyUtils myUtils = MyUtils();
The same also applies if you declare a class that extends MyUtils
in a different file.
// The superclass 'MyUtils' doesn't have a zero argument constructor
class MyExtendedUtils extends MyUtils {}
It's also impossible to call the private constructor
class MyExtendedUtils extends MyUtils {
// The class 'MyUtils' doesn't have a constructor named '_'
MyExtendedUtils() : super._();
}
Since you declare a constructor in the class, you can't use it as a mixin.
// Error: The class 'MyUtils' can't be used as a mixin because it declares a constructor
class MyAnotherUtils extends Object with MyUtils
Calling the Constructor in The Same File
However, you can call the private constructor in the same file.
MyUtils myUtils = MyUtils._();
In the same file, you can also call the private constructor inside its subclass like the code below.
class MyExtendedUtils extends MyUtils {
MyExtendedUtils() : super._();
}
If you don't want the private constructor to be called successfully even from the same file, you can throw an error inside the private constructor.
MyUtils._() {
throw new AssertionError();
}
That's how to prevent instantiation of a class in Dart.