在Dart中,const和final关键字之间有什么区别?
当前回答
编译时不知道的任何东西都应该在const上使用final。
其他回答
如果你来自c++,那么Dart中的const在c++中是constexpr,而Dart中的final在c++中是const。
以上内容仅适用于基本类型。 然而在Dart中,标记为final的对象在其成员方面是可变的。
通过@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;
}
具有final关键字的变量将在运行时初始化,并且只能分配一次。
带有const关键字的变量在编译时初始化,在运行时已经赋值。
使用final:如果你不知道它在编译时的值是多少。例如,当您需要从API获取数据时,就会在运行代码时发生这种情况。 使用const:如果您确定在运行代码时不会更改某个值。例如,当你声明一个始终保持不变的句子。
dart中的Final和const很容易混淆,以至于我们认为它们是相同的。
让我们来看看它们的区别:
附注:我包括图像而不是文本,因为我不能将信息制成表格 在Stackoverflow .md格式轻松。
何时使用哪个关键字?
一个简单的例子: 使用final:如果你不知道它在编译时的值是多少。例如,当您需要从API获取数据时,就会在运行代码时发生这种情况。
使用const:如果您确定在运行代码时不会更改某个值。例如,当你声明一个始终保持不变的句子。
https://itnext.io/difference-between-const-and-final-in-dart-78c129d0c573