0

I've just started to learn dart, but I can't understand const constructor. Can someone illustrate how to use const constructor.

Under what circumstances do I need to use it?

Mariano D'Ascanio
  • 1,202
  • 2
  • 16
  • 17
幕阜山道友
  • 753
  • 1
  • 6
  • 6

2 Answers2

2

Did you happen to stumble upon Chris Strom's post about constant constructors? What Chris Strom does in the article is an explanation of final fields, but scroll down to the comments section and there's a nice clarification of constant constructors from a certain Lasse.

lidkxx
  • 2,731
  • 2
  • 25
  • 44
1

Const objects are used in annotations:

import 'dart:mirrors';

class Foo{
  final name;
  const Foo(this.name);
}
@Foo("Bar")
class Baz{}
void main() {
  ClassMirror cm = reflectClass(Baz);
  print(cm.metadata.first.getField(#name).reflectee); // prints Bar
}

Why const objects were introduced(from the dev team):
Why does Dart have compile time constants?

Also they can provide extra optimization. For example, my dar2js experiment:
Does dart2js optimize const objects better?

Some specifics:

class Foo{
  final baz;
  const Foo(this.baz);
}

void main() {
//var foo = const Foo({"a" : 42}); //error {"a" : 42} is a mutable Map
  var foo = const Foo(const {"a" : 42}); //ok
//foo.baz["a"] = 1; //error Cannot set value in unmodifiable Map
  var bar = new Foo({"a" : 42}); //ok
//bar.baz = {"c" : 24}; //error NoSuchMethodError: method not found: 'baz='
  bar.baz["a"] = 1; //ok;
}

If class has only const constructor you still can create mutable object with new
final baz is immutable reference. But since bar is mutable, you can change baz object.

Community
  • 1
  • 1
JAre
  • 4,666
  • 3
  • 27
  • 45