在Dart中,const和final关键字之间有什么区别?
当前回答
所有这些答案我都可以用简洁的方式描述。
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是一个运行时常数。
Const表示它的初始值必须是固定的,不能是动态值;
Final意味着它的初始值必须是固定的,但可以是一个动态值,等于具有固定值的var。
代码演示
常量
void main() {
const sum = 1 + 2;
// ✅ const can not change its value
print("sum = ${sum}");
// ⚠️ Const variables must be initialized with a constant value.
const time = new DateTime.now();
// ❌ Error: New expression is not a constant expression.
print("time = ${time}");
}
最后
// new DateTime.now();
// dynamic timestamp
void main() {
final sum = 1 + 2;
// ✅ final can not change its value
print("sum = ${sum}");
final time = new DateTime.now();
// ✅ final === var with fixed value
print("time = ${time}");
}
截图
refs
https://dart.dev/guides/language/language-tour#final-and-const
如果你来自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;
}
推荐文章
- 接口方法的最终参数-有什么意义?
- 如何改变循环进度指示器的颜色
- InkWell没有显示涟漪效应
- 弹出时强制颤振导航器重新加载状态
- 颤振:扩展vs灵活
- 错误地使用父数据小部件。扩展小部件必须放置在flex小部件中
- 颤振给容器圆形边界
- Flutter: RenderBox没有布局
- 比较在Java中声明为final的==字符串
- 颤振插件未安装错误;当运行'扑动医生'时
- 我如何“休眠”Dart程序
- 在Flutter app上检查是否有网络连接
- 如何选择多行填充常量?
- Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null)
- 如何在扑动中格式化日期时间