在DART中,const个关键字和final个关键字有什么不同?

推荐答案

There is a post on dart's website and it explains it pretty well.

Final:

"final"指单个赋值:final变量或字段must具有初始值设定项.一旦赋值,最终变量的值就不能更改.最终修改为variables.


Const:

"const"在DART中有一个更为复杂和微妙的含义.常量修改为values.您可以在创建集合(如const[1,2,3])和构造对象(而不是新建)(如const Point(2,3))时使用它.在这里,const意味着对象的整个深层状态可以在编译时完全确定,并且对象将被冻结并且完全不可变.

Const对象有几个有趣的属性和限制:

它们必须从可以在编译时计算的数据创建.常量对象无权访问您在运行时需要计算的任何内容.1+2是有效的常量表达式,但new DateTime.now()不是.

它们是深刻的、可传递的不可改变的.如果有包含集合的最后一个字段,则该集合仍然可以是可变的.如果您有一个常量集合,那么其中的所有内容也必须是常量,递归地.

他们是canonicalized岁.这有点像字符串插入:对于任何给定的常量值,无论常量表达式计算多少次,都将创建并重用单个常量对象.


那么,这意味着什么呢?

Const:
If the value you have is computed at runtime (new DateTime.now(), for example), you can not use a const for it. However, if the value is known at compile time (const a = 1;), then you should use const over final. There are 2 other large differences between const and final. Firstly, if you're using const, you have to declare it as static const rather than just const. Secondly, if you have a const collection, everything inside of that is in const. If you have a final collection, everything inside of that is not final.

Final:
final should be used over const if you don't know the value at compile time, and it will be calculated/grabbed at runtime. If you want an HTTP response that can't be changed, if you want to get something from a database, or if you want to read from a local file, use final. Anything that isn't known at compile time should be final over const.


尽管如此,constfinal都不能被重新分配,但是final对象中的字段,只要它们本身不是constfinal,就可以被重新分配(与const不同).

Dart相关问答推荐

如何在 Dart 中将代码迁移到 null 安全

Dart 包对 git repo 子目录的依赖

创建默认应用时 FirebaseOptions 不能为空

flutter: 使用提供程序时,状态在热重载时丢失

在 Flutter 中将 Widget 放在 ListView 之上

在polymer和dart中将内容标签渲染为模板的一部分

Flutter-ExpansionTile 在点击时展开和折叠

如何在 Flutter 中更改 Html 小部件中的字体样式?

为http POST请求从Flutter上的TextFormField捕获数据

在Flatter中滚动列表视图时,网络图像一直消失?

如何组织混合HTTP服务器+web客户端Dart元素文件?

Flutter 错误:The _ScaffoldLayout custom multichild layout delegate forgot to lay out the following child

Flutter DataTable - 点击行

如何在 Dart 中创建 StreamTransformer?

如何提高数据与二进制数据转换的 Dart 性能?

可以在 Dart 中的抽象类中声明静态方法吗?

用于 dartlang 的 REPL

Dart: 必须取消 Stream 订阅并关闭 StreamSinks 吗?

如何使用 Dart 将字符串解析为数字?

你如何在 Dart 中构建一个单例?