在Dart中,const和final关键字之间有什么区别?
当前回答
具有final关键字的变量将在运行时初始化,并且只能分配一次。
带有const关键字的变量在编译时初始化,在运行时已经赋值。
使用final:如果你不知道它在编译时的值是多少。例如,当您需要从API获取数据时,就会在运行代码时发生这种情况。 使用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;
}
const是一个编译时常量。
final是一个运行时常数。
简单的单词:
常量
值必须在编译时已知,即来自内部文件的值。
示例:API键,应用程序支持的语言或helper文件中的任何变量,基本上是应用程序附带的任何东西。
最后
值必须在运行时已知。
它可以是上面的数据,也可以是设备信息,当应用程序启动时将被检查,或者当应用程序启动时从API或服务器加载的数据,但在应用程序准备使用之前,即你需要检查用户是否登录,你的应用程序将从服务器加载或检查会话令牌。
你不能使用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
推荐文章
- 接口方法的最终参数-有什么意义?
- 如何改变循环进度指示器的颜色
- 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)
- 如何在扑动中格式化日期时间