【问题标题】:What is the use of constant values in dart?飞镖中的常量值有什么用?
【发布时间】:2019-12-01 06:32:43
【问题描述】:

如文档中所述:

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

有人能解释一下常量值的用法吗?

【问题讨论】:

标签: dart


【解决方案1】:

我想补充一点,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 构造函数的原因,因为您需要确保可以在编译时构造对象。此外,为什么在创建对象后无法更改内部状态,如上一个答案所示。

【讨论】:

    【解决方案2】:
    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;
    值是枚举、列表、映射、类等的实例。

    【讨论】:

      【解决方案3】:

      这是一个简单的例子,希望能解释清楚:

      var foo = [10,11];
      var bar = const [20,21];
      
      print(foo.toString()); // [10,11]
      print(bar.toString()); // [20,21]
      
      foo.add(12);
      print(foo.toString()); // [10,11,12]
      
      bar.add(22); // ERROR! Not allowed because the array itself is immutable
      
      bar = [30,31]; // Reassignment to new array allowed because bar is a var
      
      bar.add(32) // Allowed because the array itself was not declared const
      print(bar.toString()); // [30,31,32]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 2021-03-08
        • 2019-10-24
        • 1970-01-01
        • 1970-01-01
        • 2020-08-31
        • 2019-09-30
        相关资源
        最近更新 更多