43

I've seen this code can anyone please explain to me what the AppTheme._() means, as I've read about its singleton class in dart but I really can't understand how it works.

class AppTheme {
  AppTheme._();

  static const Color notWhite = Color(0xFFEDF0F2);
  static const Color nearlyWhite = Color(0xFFFEFEFE);
  static const Color white = Color(0xFFFFFFFF);
  static const Color nearlyBlack = Color(0xFF213333);

  ...
}
Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
Shadi Ossaili
  • 545
  • 1
  • 4
  • 6
  • Possible duplicate of [The difference between the use of constructor " className() and className.\_()](https://stackoverflow.com/questions/57812052/the-difference-between-the-use-of-constructor-classname-and-classname) – jamesdlin Sep 10 '19 at 22:33

2 Answers2

74

AppTheme._(); is a named constructor (another examples might be the copy constructor on some objects in the Flutter framework: ThemeData.copy(...);).

In dart, if the leading character is an underscore, then the function/constructor is private to the library. That's also the case here, and the underscore is also the only character, so I'd imagine whoever wrote this constructor didn't plan for that constructor to ever be called at all.

The AppTheme._(); isn't necessary unless you don't want AppTheme to ever be accidentally instantiated using the implicit default constructor.

Sub 6 Resources
  • 1,674
  • 15
  • 31
  • Thank you that was helpful! , yes I guess there is no need for this constructor. – Shadi Ossaili Sep 10 '19 at 21:32
  • No problem! Glad I could help! Also, welcome to Stack Overflow! Don't forget to mark my answer as correct if it helped you. – Sub 6 Resources Sep 10 '19 at 21:35
  • 6
    This is slightly inaccurate. A leading underscore makes the name private to the *library*, which *usually* (but not always) means private to the file. Additionally, omitting `AppTheme._()` isn't exactly the same; as you said, it's there to prevent `AppState` from being instantiated. If there are no constructors, then there will be an implicit default constructor. – jamesdlin Sep 10 '19 at 22:39
  • Ah yeah, that's right. Thanks @jamesdlin. Updated my answer to reflect this. – Sub 6 Resources Sep 10 '19 at 22:47
8

It is to make the class non-instantiable.

More on https://www.woolha.com/tutorials/dart-prevent-instantiation-of-class#:~:text=Creating%20Private%20Constructor%20to%20Prevent,(underscore)%20which%20means%20private.

Also, I think this summarise why we need it in the first place "If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. " from https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors