Dart 编程中的 const 关键字

Dart 为我们提供了两种方式来声明具有固定值的变量。其中一种方法是使用 const 关键字声明变量,另一种方法是使用 final 关键字声明变量。

应该注意的是,它们都提供了一种保证,即一旦将值分配给与它们一起的变量,它就不会改变,但它们确实彼此略有不同。

常量

不能为使用 const 关键字声明的变量分配任何其他值。此外,该变量被称为编译时常量,这意味着必须在编译程序时声明其值。

例子

考虑下面显示的示例 -

void main(){
   const name = "mukul";
   print(name);

   const marsGravity = 3.721;
   print(marsGravity);
}

输出

mukul
3.721

如果我们尝试为上面声明的两个变量中的任何一个分配任何其他值,编译器将抛出错误。

例子

考虑下面显示的示例 -

void main(){
   const name = "mukul";
   print(name);

   name = "mayank";
   print(name);
}

输出

Error: Can't assign to the const variable 'name'.
name = "mayank";
^^^^
Error: Compilation failed.

还应该注意的是,我们可以在编译时声明对象并将它们分配给一个常量变量。

例子

考虑下面显示的例子 -

import 'dart:math';
void main(){
   const Rectangle bounds = const Rectangle(0, 0, 3, 4);
   print(bounds);
}

输出

Rectangle (0, 0) 3 x 4