Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a private constructor in dart?

Tags:

dart

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?

like image 768
Ahmed Kamal Avatar asked Mar 13 '19 13:03

Ahmed Kamal


People also ask

Is private constructor possible?

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.

What is the use of private constructor in dart?

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.

How do you call a private constructor in Flutter?

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.

How do you make a constructor private?

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.


1 Answers

Just create a named constructor that starts with _

class Foo {   Foo._() {} } 

then the constructor Foo._() will be accessible only from its class (and library).

like image 56
Mattia Avatar answered Sep 21 '22 05:09

Mattia