提问者:小点点

有人能说明如何使用const构造函数吗?在什么情况下我需要使用它?[副本]


我刚开始学习飞镖,但我不懂常量构造函数。有人能说明如何使用const构造函数吗。

我需要在什么情况下使用它?


共2个答案

匿名用户

你是否碰巧看到了Chris Strom关于常量构造函数的帖子?Chris Strom在文章中做的是对final字段的解释,但是向下滚动到评论部分,有一个对某个类的常量构造函数的很好的解释。

匿名用户

Const对象用在注释中:

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
}

为什么引入const对象(来自开发团队):
为什么Dart有编译时间常量?

它们还可以提供额外的优化。例如,我的dar2js实验:
dart2js是否更好地优化了const对象?

一些细节:

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;
}

如果class只有const构造函数,您仍然可以使用new
创建可变对象,最终baz是不可变引用。但是由于bar是可变的,您可以更改baz对象。