# 变量、常量
# Dart 变量
Dart是个强大的脚本语言,可以不预先定义变量类型,可以自动推到数据类型。
Dart中定义变量可以通过var
关键字,也可以通过类型申明变量。
var str = 'This is var.';
String str1 = 'This is string.';
int num = 123;
注意:dart中有类型校验。
var
和数据类型不要一起写。- 使用数据类型定义变量赋值必须符合该数据类型。
- 使用
var
定义的变量,一旦程序推导出数据类型,之后赋值必须符合该数据类型。
# Dart 常量
Dart中常量使用const
修饰,常量不可被重新赋值。
const PI = 3.1415926;
const double e = 2.71828;
// PI = 123; //报错
// Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
// Try adding the name of the type of the variable or the keyword 'var'.dart(missing_const_final_var_or_type)
// The name 'PI' is already defined.
// Try renaming one of the declarations.
除了const
还可使用final
修饰常量:
final PI = 3.1415926;
final t = new DateTime.now();
print(t);
//2020-05-20 23:34:02.932543
const
与final
区别:
final
可以不用一开始就赋值,使用时再赋值只能赋值一次;final
不仅有const
编译时常量的特性,最重要的它是运行时常量,并且final
是惰性初始化,即在运行时第一次使用才初始化赋值。