Dart 关键字
Keywords
The following table lists the words that the Dart language treats specially.
| abstract 2 | else | import 2 | show 1 |
| as 2 | enum | in | static 2 |
| assert | export 2 | interface 2 | super |
| async 1 | extends | is | switch |
| await 3 | extension 2 | late 2 | sync 1 |
| break | external 2 | library 2 | this |
| case | factory 2 | mixin 2 | throw |
| catch | false | new | true |
| class | final | null | try |
| const | finally | on 1 | typedef 2 |
| continue | for | operator 2 | var |
| covariant 2 | Function 2 | part 2 | void |
| default | get 2 | required 2 | while |
| deferred 2 | hide 1 | rethrow | with |
| do | if | return | yield 3 |
| dynamic 2 | implements 2 | set 2 | |
Avoid using these words as identifiers. However, if necessary, the keywords marked with superscripts can be identifiers:
-
Words with the superscript 1 are contextual keywords, which have meaning only in specific places. They’re valid identifiers everywhere.
-
Words with the superscript 2 are built-in identifiers. These keywords are valid identifiers in most places, but they can’t be used as class or type names, or as import prefixes.
-
Words with the superscript 3 are limited reserved words related to asynchrony support. You can’t use
await
oryield
as an identifier in any function body marked withasync
,async*
, orsync*
.
All other words in the table are reserved words, which can’t be identifiers.
避免将这些单词用作标识符。但是,如有必要,用上标标记的关键字可以是标识符:
上标1的单词是上下文关键字,只有在特定的地方才有意义。它们在任何地方都是有效的标识符。
上标为2的单词是内置标识符。这些关键字在大多数地方都是有效标识符,但不能用作类或类型名,也不能用作导入前缀。
上标为3的字是与异步支持相关的有限保留字。在任何标记为async、async或sync的函数体中,都不能使用wait或yield作为标识符。
表中的所有其他字都是保留字,不能作为标识符。
dynamic
如果希望动态改变参数的类型,可以使用dynamic来声明变量:
但是在开发中, 通常情况下不使用dynamic, 因为类型的变量会带来潜在的危险
dynamic name = 'coderwhy';
print(name.runtimeType); // String
name = 18;
print(name.runtimeType); // int
final&const的使用
final和const都是用于定义常量的, 也就是定义之后值都不可以修改
final name = 'coderwhy';
name = 'kobe'; // 错误做法
const age = 18;
age = 20; // 错误做法
final和const有什么区别呢?
const在赋值时, 赋值的内容必须是在编译期间就确定下来的
final在赋值时, 可以动态获取, 比如赋值一个函数
String getName() {
return 'coderwhy';
}
main(List<String> args) {
const name = getName(); // 错误的做法, 因为要执行函数才能获取到值
final name = getName(); // 正确的做法
}
final和const小案例:
首先, const是不可以赋值为DateTime.now()
其次, final一旦被赋值后就有确定的结果, 不会再次赋值
// const time = DateTime.now(); // 错误的赋值方式
final time = DateTime.now();
print(time); // 2019-04-05 09:02:54.052626
sleep(Duration(seconds: 2));
print(time); // 2019-04-05 09:02:54.052626
const放在赋值语句的右边,可以共享对象,提高性能:
class Person {
const Person();
}
main(List<String> args) {
final a = const Person();
final b = const Person();
print(identical(a, b)); // true
final m = Person();
final n = Person();
print(identical(m, n)); // false
}