在Dart中,静态成员,最终成员和const成员在编译时有什么区别?

Joe*_*röm 0 access-modifiers dart flutter

就像标题所暗示的那样,在Dart中,编译时的static,final和const有什么区别?

它们何时计算,何时为每种类型分配内存?大量使用静态变量会导致性能问题或OOM吗?

Gün*_*uer 5

static用来声明类级别的成员(方法,字段,获取器/设置器)。它们在类的名称空间中。只能从类(而不是子类)内部或以类名作为前缀来访问它们。

class Foo {
  static bar() => print('bar');

  void baz() => bar(); // ok
}

class Qux extens Foo {
  void quux() => bar(); // error. There is no `bar()` on the `Qux` instance
}

main() {
  var foo = Foo();
  foo.bar(); // error. There is no `bar` on the `Foo` instance.
  Foo.bar(); // ok
}
Run Code Online (Sandbox Code Playgroud)

const用于编译时间常数。Dart允许使用一组有限的表达式来计算编译时间常数。 const实例被规范化。这意味着规范化了多个const Text('foo')(具有相同的'foo'参数值),并且无论此代码在您的应用程序中出现的位置和频率如何,都只会创建一个实例。

class Foo {
  const Foo(this.value);

  // if there is a const constructor then all fields need to be `final`
  final String value;
}
void main() {
  const bar1 = Foo('bar');
  const bar2 = Foo('bar');
  identical(bar1, bar2); // true 
}
Run Code Online (Sandbox Code Playgroud)

final 仅表示只能在声明时分配给它。

例如,对于字段,这意味着在字段初始值设定项中,通过使用分配的构造函数参数this.foo,或在构造函数初始值设定项列表中,但在执行构造函数主体时不再有效。

void main() {
  final foo = Foo('foo');
  foo = Foo('bar'); // error: Final variables can only be initialized when they are introduced
}

class Foo {
  final String bar = 'bar';
  final String baz;
  final String qux;

  Foo(this.baz);
  Foo.other(this.baz) : qux = 'qux' * 3;
  Foo.invalid(String baz) {
  // error: Final `baz` and `qux` are not initialized
    this.baz = baz;         
    this.qux = 'qux' * 3;
  }
}
Run Code Online (Sandbox Code Playgroud)