dart中常量值的用途是什么?

时间:2019-12-01 06:32:43

标签: dart

如文档所述:

  

const关键字不仅用于声明常量变量。您也可以使用它来创建常量值,以及声明创建常量值的构造函数。任何变量都可以具有恒定值。

有人可以解释常量值的使用吗?

2 个答案:

答案 0 :(得分:1)

void main() {
  simpleUse();
  finalUse();
  constUse();
}

simpleUse() {
  print("\nsimple declaration");
  var x = [10];
  print('before: $x');
  x = [5];//changing reference allowed
  x.add(10);//changing content allowed
  print('after: $x');
}

finalUse() {
  print("\nfinal declaration");
  final x = [10];
  print('before: $x');

  // x = [10,20]; //nope changing reference is not allowed for final declaration

  x.add(20); //changing content is allowed
  print('after: $x');
}

constUse() {
  print("\nconst declaration");
  const x = [10];
  print('before: $x');

  // x = [10,20]; //nope -> changing reference is not allowed for final declaration

  // x.add(20);//nope -> changing content is not allowed
  print('after: $x');
}

此外,变量是简单的值,例如x = 10;
值是枚举,列表,映射,类等的实例。

答案 1 :(得分:0)

我想补充一点,const的另一点是保证每次使用相同的参数构造对象时,都会获得相同的对象实例:

class Test {
  final int value; 
  const Test(this.value);
}

void main() {
  print(Test(5).hashCode == Test(5).hashCode); // false
  print((const Test(5)).hashCode == (const Test(5)).hashCode); // true
}

这就是为什么很难为所有对象创建const构造函数的原因,因为您需要确保可以在编译时构造该对象。同样,为什么在创建对象后无法更改内部状态,如先前的回答也显示出来。

相关问题