在这一章节中,我们将详细探讨 Dart 编程语言中的关键字。这些关键字具有特殊的含义,并且不能被用作标识符(如变量名、函数名等)。理解这些关键字对于编写有效的 Dart 代码至关重要。
abstract
abstract 关键字用于定义抽象类或方法。抽象类不能实例化,只能被继承。抽象方法没有实现,需要子类提供具体实现。
// www.javascriptcn.com code example
abstract class Animal {
void makeSound(); // 抽象方法
}
class Dog extends Animal {
@override
void makeSound() {
print("Woof!");
}
}as
as 关键字用于类型转换。它告诉编译器你希望将一个对象视为特定类型。
dynamic obj = "Hello, Dart!"; String str = obj as String; print(str); // 输出 "Hello, Dart!"
assert
assert 关键字用于调试时检查条件是否为真。如果条件不满足,程序将抛出异常并停止执行。
void main() {
int age = -5;
assert(age >= 0, "年龄不能为负数");
}async 和 await
async 和 await 关键字用于异步编程。async 修饰的函数返回一个 Future 对象,而 await 用于等待 Future 完成。
Future<void> fetchData() async {
var data = await fetchSomeData();
print(data);
}bool
bool 是布尔类型,表示逻辑值 true 或 false。
bool isRaining = true;
if (isRaining) {
print("记得带伞!");
}break
break 关键字用于终止循环或 switch 语句。当遇到 break 时,控制流会跳出当前结构。
for (int i = 0; i < 10; i++) {
if (i == 5) break;
print(i);
}
// 输出:0 1 2 3 4byte
虽然 Dart 没有专门的 byte 类型,但可以使用 int 来处理字节数据。Dart 中整数默认是64位的,也可以用 Uint8List 处理字节数据。
var byteArray = Uint8List.fromList([1, 2, 3, 4]);
case
case 关键字用于 switch 语句,用来指定每个分支的条件。
// www.javascriptcn.com code example
void main() {
int number = 2;
switch (number) {
case 1:
print("数字是1");
break;
case 2:
print("数字是2");
break;
default:
print("其他数字");
}
}catch
catch 关键字与 try 一起使用,用于捕获 try 块中可能发生的异常。
try {
int result = 10 ~/ 0;
} catch (e) {
print(e); // 输出异常信息
}class
class 关键字用于定义类,类是面向对象编程的基础。
// www.javascriptcn.com code example
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print("我的名字叫 $name,今年 $age 岁。");
}
}const
const 关键字用于创建常量。常量在编译时确定其值,不可改变。
const pi = 3.14;
continue
continue 关键字用于跳过当前循环迭代并继续下一个迭代。
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
print(i); // 输出奇数:1 3 5 7 9
}covariant
covariant 关键字用于标记参数,以便在子类中覆盖父类的方法时能够进行类型检查。
class Base {
void method(covariant Base arg) {}
}
class Derived extends Base {
@override
void method(Derived arg) {}
}default
default 关键字用于 switch 语句,当所有 case 都不符合时作为默认分支。
// www.javascriptcn.com code example
void main() {
int number = 10;
switch (number) {
case 1:
print("数字是1");
break;
case 2:
print("数字是2");
break;
default:
print("数字不是1也不是2");
}
}deferred
deferred 关键字用于延迟加载库,仅在需要时才会加载。
import 'package:deferred/async.dart' deferred as async;
do
do 关键字用于 do-while 循环,先执行循环体再判断条件。
int count = 0;
do {
print(count++);
} while (count < 5);dynamic
dynamic 关键字用于声明动态类型,允许任何类型的赋值。
dynamic value = "Hello"; value = 123;
else
else 关键字用于 else 子句,与 if 语句配合使用。
int age = 20;
if (age < 18) {
print("未成年");
} else {
print("成年");
}enum
enum 关键字用于定义枚举类型,枚举类型是一组命名的常量集合。
enum Color { red, green, blue }
void main() {
Color myColor = Color.red;
print(myColor); // 输出:Color.red
}export
export 关键字用于导出库中的成员到另一个库中。
// 在 a.dart 文件中 export 'b.dart';
extends
extends 关键字用于继承基类。
// www.javascriptcn.com code example
class Animal {
void eat() {
print("吃东西");
}
}
class Dog extends Animal {
void bark() {
print("汪汪叫");
}
}extension
extension 关键字用于扩展类的功能,而无需修改原始类。
// www.javascriptcn.com code example
extension StringExtension on String {
String reverse() {
return this.split('').reversed.join('');
}
}
void main() {
String str = "hello";
print(str.reverse()); // 输出:olleh
}external
external 关键字用于声明外部方法,通常用于绑定 C/C++ 函数。
external int externalFunction();
factory
factory 关键字用于创建工厂构造函数,用于返回缓存的对象实例。
// www.javascriptcn.com code example
class Logger {
final String name;
bool mute = false;
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name]!;
} else {
final logger = Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String message) {
if (!mute) {
print(message);
}
}
}false
false 是布尔类型的一个值,表示假或否定状态。
bool isTrue = false;
if (!isTrue) {
print("isTrue 是 false");
}final
final 关键字用于声明最终变量,一旦赋值就不能更改。
final String name = "Alice"; name = "Bob"; // 错误,不能重新赋值
finally
finally 关键字用于确保无论 try-catch 结果如何都会被执行的代码块。
try {
// 执行一些操作
} catch (e) {
// 处理异常
} finally {
// 总会执行的代码
}for
for 关键字用于 for 循环,用于遍历集合或重复执行一段代码。
for (int i = 0; i < 5; i++) {
print(i);
}function
Dart 没有单独的 function 关键字,而是使用 void 或其他类型来声明函数。
int add(int a, int b) {
return a + b;
}get
get 关键字用于定义 getter 方法,用于获取属性的值。
class Rectangle {
double _width;
double _height;
Rectangle(this._width, this._height);
double get area => _width * _height;
}hide
hide 关键字用于隐藏导入库中的成员。
import 'package:lib1/lib1.dart' hide foo;
if
if 关键字用于条件语句,根据条件执行不同的代码块。
int age = 20;
if (age >= 18) {
print("成年人");
} else {
print("未成年人");
}implements
implements 关键字用于实现接口,确保类实现了接口中定义的所有方法。
// www.javascriptcn.com code example
abstract class Printable {
void printMe();
}
class Circle implements Printable {
@override
void printMe() {
print("这是一个圆");
}
}import
import 关键字用于导入库中的成员。
import 'dart:math';
in
in 关键字用于 for-in 循环,用于遍历集合中的元素。
List<int> numbers = [1, 2, 3, 4, 5];
for (int number in numbers) {
print(number);
}index
虽然 Dart 没有 index 关键字,但在列表和数组中可以通过索引来访问元素。
List<String> fruits = ['apple', 'banana', 'cherry']; print(fruits[1]); // 输出:banana
interface
Dart 没有单独的 interface 关键字,而是通过抽象类或接口来定义接口。
abstract class Drawable {
void draw();
}is
is 关键字用于类型测试,判断一个对象是否属于某种类型。
Object obj = "Hello";
if (obj is String) {
print("这是一个字符串");
}library
library 关键字用于定义库,库是一个包含相关代码的模块。
library my_library;
mixin
mixin 关键字用于定义混入类,混入类可以添加到其他类中,以增强其功能。
// www.javascriptcn.com code example
mixin Fluffy {
void makeFluffy() {
print("变得蓬松");
}
}
class Cat with Fluffy {
void meow() {
print("喵喵叫");
}
}
void main() {
Cat cat = Cat();
cat.makeFluffy(); // 输出:变得蓬松
cat.meow(); // 输出:喵喵叫
}new
虽然 Dart 2.0 及以上版本已弃用 new 关键字,但在早期版本中用于创建对象。
var list = new List<String>(); // 在 Dart 2.0+ 版本中可省略 new
null
null 表示空值或未定义值。
String? name; print(name ?? "未知"); // 输出:未知
null-aware
Dart 提供了多种 null-aware 操作符(如 ?., ??, ??=),用于处理可能为 null 的值。
String? name; print(name?.toUpperCase() ?? "未知"); // 输出:未知
on
on 关键字用于指定在 catch 子句中捕获特定类型的异常。
try {
// 执行一些可能会抛出异常的操作
} on ArgumentError catch (e) {
print("参数错误:$e");
}operator
operator 关键字用于定义自定义运算符。
// www.javascriptcn.com code example
class Vector {
final int x;
final int y;
Vector(this.x, this.y);
Vector operator +(Vector v) {
return Vector(x + v.x, y + v.y);
}
}
void main() {
Vector v1 = Vector(2, 3);
Vector v2 = Vector(1, 1);
Vector v3 = v1 + v2;
print(v3.x); // 输出:3
print(v3.y); // 输出:4
}part
part 关键字用于指示一个文件是另一个库的一部分。
// 在 main.dart 文件中 library my_library; part 'my_library_part.dart';
part of
part of 关键字用于指示一个文件属于某个库的一部分。
// 在 my_library_part.dart 文件中 part of my_library;
rethrow
rethrow 关键字用于在 catch 块中重新抛出捕获的异常。
void main() {
try {
throw Exception("发生错误");
} catch (e) {
print("捕获到异常:$e");
rethrow;
}
}return
return 关键字用于从函数返回一个值。
int multiply(int a, int b) {
return a * b;
}
void main() {
int result = multiply(3, 4);
print(result); // 输出:12
}set
set 关键字用于定义 setter 方法,用于设置属性的值。
// www.javascriptcn.com code example
class Rectangle {
double _width;
double _height;
Rectangle(this._width, this._height);
set width(double value) {
_width = value;
}
set height(double value) {
_height = value;
}
}show
show 关键字用于显示导入库中的成员。
import 'package:lib1/lib1.dart' show foo;
static
static 关键字用于定义静态成员,静态成员属于类而不是类的实例。
// www.javascriptcn.com code example
class Counter {
static int count = 0;
Counter() {
count++;
}
}
void main() {
Counter c1 = Counter();
Counter c2 = Counter();
print(Counter.count); // 输出:2
}super
super 关键字用于引用父类的成员。
// www.javascriptcn.com code example
class Animal {
void eat() {
print("吃东西");
}
}
class Dog extends Animal {
@override
void eat() {
super.eat();
print("汪汪叫");
}
}switch
switch 关键字用于多分支选择结构,根据表达式的值选择执行相应的分支。
// www.javascriptcn.com code example
void main() {
int number = 2;
switch (number) {
case 1:
print("数字是1");
break;
case 2:
print("数字是2");
break;
default:
print("其他数字");
}
}sync*
sync* 关键字用于定义同步生成器函数,生成器函数可以产生一系列值。
// www.javascriptcn.com code example
Iterable<int> generateNumbers(int n) sync* {
for (int i = 0; i < n; i++) {
yield i;
}
}
void main() {
Iterable<int> numbers = generateNumbers(5);
print(numbers.toList()); // 输出:[0, 1, 2, 3, 4]
}this
this 关键字用于引用当前类的实例成员。
// www.javascriptcn.com code example
class Point {
double x;
double y;
Point(this.x, this.y);
double distanceTo(Point other) {
double dx = this.x - other.x;
double dy = this.y - other.y;
return sqrt(dx * dx + dy * dy);
}
}throw
throw 关键字用于抛出异常。
void checkAge(int age) {
if (age < 18) {
throw ArgumentError("年龄必须大于等于18");
}
}true
true 是布尔类型的一个值,表示真或肯定状态。
bool isAdult = true;
if (isAdult) {
print("成年人");
}try
try 关键字用于 try-catch 结构,用于捕获可能发生的异常。
try {
// 执行一些可能会抛出异常的操作
} catch (e) {
print("捕获到异常:$e");
}typedef
typedef 关键字用于创建类型别名。
typedef DoubleToInt = int Function(double value); DoubleToInt convert = (double value) => value.toInt();
var
var 关键字用于自动推断变量的类型。
var name = "Alice"; print(name.runtimeType); // 输出:String
void
void 关键字用于表示无返回值的函数。
void printName(String name) {
print(name);
}这些关键字构成了 Dart 语言的核心部分,理解和掌握它们对于编写高效、清晰的代码至关重要。在接下来的学习中,我们将进一步探索这些关键字的具体应用和最佳实践。