在Dart中,const和final关键字之间有什么区别?


当前回答

你不能使用final对象初始化const对象。例如:

  final myConst = 1;
  const myFinal = 2;

  final a = myConst; // possible
  final b = myFinal; // possible
  const c = myConst; // this is not possible
  const d = myFinal; // possible

其他回答

所有这些答案我都可以用简洁的方式描述。

const list = [1, 2, 3];

变量/标识符和值都是const。Like - const list = const [1,2,3] 这就是为什么他们不允许被重新分配。 很适合全局变量。 可以将其用作类变量,但必须设置为静态。Like - static const list =[1,2,3]。

vs:

final list = [1, 2, 3];

变量/标识符是const,而值不是。Like - const list = [1,2,3] 这就是为什么我们可以执行like - list.add(4)

编译时不知道的任何东西都应该在const上使用final。

如果你来自c++,那么Dart中的const在c++中是constexpr,而Dart中的final在c++中是const。

以上内容仅适用于基本类型。 然而在Dart中,标记为final的对象在其成员方面是可变的。

常量

Value必须在编译时已知,const birthday = "2008/12/25"初始化后不能更改。


最后

值必须在运行时已知,最终生日= getBirthDateFromDB()初始化后不能更改。

通过@Meyi扩展答案

final variable can only be set once and it is initialized when accessed.(for example from code section below if you use the value of biggestNumberOndice only then the value will be initialized and memory will be assigned). const is internally final in nature but the main difference is that its compile time constant which is initialized during compilation even if you don't use its value it will get initialized and will take space in memory. Variable from classes can be final but not constant and if you want a constant at class level make it static const.

代码:

void main() {

    // final demonstration
    final biggestNumberOndice = '6';
    //  biggestNumberOndice = '8';     // Throws an error for reinitialization

    // const
    const smallestNumberOnDice = 1;

}

class TestClass {

    final biggestNumberOndice = '6';

    //const smallestNumberOnDice = 1;  //Throws an error
    //Error .  only static fields can be declared as constants.

    static const smallestNumberOnDice = 1;
}