0

I was looking for codes to understand the difference between final and const in dart. After I found some code blocks and changed a bit, the outputs were surprising for me. How to explain these outputs? What causes this difference?

void main() {
  final list1 = [1, 2];
  final list2 = [1, 2];

  print(list1);
  print(list2);
  print(list1 == list2); //false

  const list3 = [1, 2];
  const list4 = [1, 2];

  print(list3);
  print(list4);
  print(list3 == list4); //true
}

1 Answers1

3

const means the object is created at compile time instead of when the program is running. Dart does also guarantee that if you create two const objects with the same arguments, it will both points to the same compile time object. This optimization is possible since const objects MUST be immutable and we can therefore safely just share the same instance multiple times.

The == operator will by default (and such also on List) check if two objects are the same as in the same physical object in memory.

Since your two const created lists are created with the same objects, the two lists variables, list3 and list4, will end up pointing to the same exact object created by the compiler and therefore list3 == list4 is going to be true.

julemand101
  • 28,470
  • 5
  • 52
  • 48