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
  • 15,737
  • 15
  • 35
  • 52

1 Answers1

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
  • 904
  • 5
  • 16
  • 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