Is it possible to have a private constructor in dart?

Dart

Dart Problem Overview


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?

Dart Solutions


Solution 1 - Dart

Just create a named constructor that starts with _

class Foo {
  Foo._() {}
}

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

Solution 2 - Dart

A method without any code must be something like this

class Foo {
  Foo._();
}

Solution 3 - Dart

Yes, It is possible, wanna add more information around it.

A constructor can be made private by using (_) underscore operator which means private in dart.

So a class can be declared as

class Foo {
  Foo._() {}
}

so now, The class Foo doesn't have a default constructor

Foo foo = Foo(); // It will give compile time error

The same theory applied while extending class also, It's also impossible to call the private constructor if it declares in a separate file.

class FooBar extends Foo {
    FooBar() : super._(); // This will give compile time error.
  }

But both above functionality works if we use them in the same class or file respectively.

  Foo foo = Foo._(); // It will work as calling from the same class

and

 class FooBar extends Foo {
    FooBar() : super._(); // This will work as both Foo and FooBar are declared in same file. 
  }

Solution 4 - Dart

just use abstract class. Because you can't instantiate abstract class

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAhmed KamalView Question on Stackoverflow
Solution 1 - DartMattiaView Answer on Stackoverflow
Solution 2 - DartcesarView Answer on Stackoverflow
Solution 3 - DartJitesh MohiteView Answer on Stackoverflow
Solution 4 - DartTokiniaina Eddy AndriamiandrisView Answer on Stackoverflow