I'm able to do something like the following in TypeScript
class Foo { private constructor () {} }
so this constructor
is accessible only from inside the class itself.
How to achieve the same functionality in Dart?
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
How do you make a private constructor in dart classes? Generally, a Private constructor allows you not to create an object or instance of a class. Private constructors are useful to create a Singleton pattern.
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.
Java allows us to declare a constructor as private. We can declare a constructor private by using the private access specifier. Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we can use this private constructor in Singleton Design Pattern.
Just create a named constructor that starts with _
class Foo { Foo._() {} }
then the constructor Foo._()
will be accessible only from its class (and library).
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