1

From Why does Dart have compile time constants?:

Dart has the concept of compile-time constants. A compile-time constant is parsed and created at compile time, and canonicalized.

For example, here is a const constructor for Point:

class Point {
  final num x, y;
  const Point(this.x, this.y);
}

And here's how you use it:

main() {
  var p1 = const Point(0, 0);
  var p2 = const Point(0, 0);
  print(p1 == p2); // true
  print(p1 === p2); // true
}

This code snippet was from Stack Overflow I am reusing this good example, thanks again. Const I have noticed is used alot in flutter widgets.

Does that mean that we can use const to create Singleton Objects?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

2 Answers2

0

To create a singleton, check out the following answer: How do you build a Singleton in Dart?

There is a difference between const and final, which can be found here: What is the difference between the "const" and "final" keywords in Dart?

But in short, you can't use const for singleton objects, as the object is not a compile time constant. You'll need to use final.

GLJ
  • 1,074
  • 1
  • 9
  • 17
  • Thanks a lot for the useful reply, appreciate it. I did not know this especially When you declare a list as final and you can still append values to it however when its marked const you can not even add new values: Almost like final is like the const in javascript and the const is the real const thats missin gin javascript – Solen Dogan May 09 '21 at 11:52
0

No. const constructors have a very different purpose from the singleton pattern.

A singleton aims to ensure that only one instance of the class exists in the program. For example, you have an Area class in your program. You want only one area object instance to exist so you implement it as a singleton (Look link in another answer).

Then, every time you call Area() it returns the same instance:

Area().setPoint(const Point(1, 2));
Area().setPoint(const Point(11, 12));
Area().setPoint(const Point(21, 22));

Now, the purpose of const is to improve performance. Flutter will not rebuild the widget if it is defined as const. But you can create as many different instances of Point as you wish.

Yuriy N.
  • 4,936
  • 2
  • 38
  • 31