Dart 语法 (Dart Syntax)¶
1. 变量与常量 (Variables and Constants)¶
1.1 变量声明 (Variable Declaration)¶
var name = 'Xihai'; // 类型自动推断为 String (Type inferred as String)
int age = 30; // 显式指定类型 (Explicitly specifying the type)
double height = 1.75;
bool isStudent = true;
1.2 常量声明 (Constant Declaration)¶
final String city = 'Beijing'; // 运行时常量 (Runtime constant)
const double pi = 3.14159; // 编译时常量 (Compile-time constant)
2. 数据类型 (Data Types)¶
int count = 10; // 整数类型 (Integer)
double price = 19.99; // 双精度浮点数 (Double)
String message = 'Hello, Dart!'; // 字符串类型 (String)
bool isActive = true; // 布尔类型 (Boolean)
List<String> fruits = ['Apple', 'Banana', 'Orange']; // 列表 (List)
Map<String, int> scores = {'Math': 95, 'English': 88}; // 映射 (Map)
Set<String> colors = {'red', 'green', 'blue'}; // 集合 (Set)
dynamic variable = 'Hello'; // 动态类型 (Dynamic type)
Object obj = 'Any type'; // 对象类型,所有类型的基类 (Object type, base class of all Dart types)
3. 函数 (Functions)¶
3.1 基本函数 (Basic Function)¶
void printMessage() {
print('Hello, Dart!'); // 打印信息 (Print message)
}
int add(int a, int b) {
return a + b; // 返回两个数的和 (Return the sum of two numbers)
}
3.2 箭头函数 (Arrow Functions)¶
int multiply(int a, int b) => a * b; // 乘法运算的简写形式 (Short form for multiplication)
3.3 可选命名参数 (Optional Named Parameters)¶
void greet({String? name, int? age}) {
print('Hello $name, you are $age years old.'); // 打印问候语 (Print greeting)
}
greet(name: 'Xihai', age: 30); // 调用函数并传递参数 (Call function with arguments)
3.4 可选位置参数 (Optional Positional Parameters)¶
void printInfo(String name, [int? age]) {
print('Name: $name, Age: $age'); // 打印姓名和年龄 (Print name and age)
}
printInfo('Xihai', 30); // 调用函数并传递位置参数 (Call function with positional arguments)
## 4. 控制流语句 (Control Flow Statements)
### 4.1 条件语句 (Conditional Statements)
```dart
if (age > 18) {
print('Adult'); // 如果年龄大于18,打印“成人” (Print "Adult" if age is greater than 18)
} else if (age > 12) {
print('Teenager'); // 如果年龄大于12,打印“青少年” (Print "Teenager" if age is greater than 12)
} else {
print('Child'); // 否则打印“儿童” (Otherwise, print "Child")
}
4.2 switch 语句 (Switch Statement)¶
switch (age) {
case 18:
print('Just an adult'); // 如果年龄是18,打印“刚成年” (Print "Just an adult" if age is 18)
break;
case 30:
print('In your prime'); // 如果年龄是30,打印“正值壮年” (Print "In your prime" if age is 30)
break;
default:
print('Age is just a number'); // 默认情况下,打印“年龄只是个数字” (By default, print "Age is just a number")
}
4.3 三元运算符 (Ternary Operator)¶
String type = age > 18 ? 'Adult' : 'Not an Adult'; // 三元运算符检查年龄并返回相应的字符串 (Ternary operator checks age and returns the corresponding string)
5. 循环语句 (Loop Statements)¶
5.1 for 循环 (For Loop)¶
for (int i = 0; i < 5; i++) {
print('i = $i'); // 打印i的值 (Print the value of i)
}
5.2 for-in 循环 (For-in Loop)¶
for (var fruit in fruits) {
print(fruit); // 遍历列表并打印每个水果 (Iterate over the list and print each fruit)
}
5.3 while 循环 (While Loop)¶
int i = 0;
while (i < 5) {
print('i = $i'); // 当i小于5时打印i的值 (Print the value of i while i is less than 5)
i++; // 递增i的值 (Increment the value of i)
}
5.4 do-while 循环 (Do-while Loop)¶
int j = 0;
do {
print('j = $j'); // 打印j的值 (Print the value of j)
j++; // 递增j的值 (Increment the value of j)
} while (j < 5); // 当j小于5时继续循环 (Continue looping while j is less than 5)
6. 类与对象 (Classes and Objects)¶
6.1 定义类 (Defining a Class)¶
class Person {
String name; // 属性:姓名 (Property: name)
int age; // 属性:年龄 (Property: age)
Person(this.name, this.age); // 构造函数 (Constructor)
// 命名构造函数 (Named Constructor)
Person.fromJson(Map<String, dynamic> json)
: name = json['name'],
age = json['age'];
void sayHello() { // 方法:问候 (Method: greeting)
print('Hello, my name is $name.'); // 打印问候信息 (Print greeting message)
}
}
// 创建对象 (Creating an Object)
var person = Person('Xihai', 30);
person.sayHello(); // 调用方法 (Calling a Method)
7. 异步编程 (Asynchronous Programming)¶
7.1 使用 async/await (Using async/await)¶
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // 模拟一个耗时操作 (Simulate a time-consuming operation)
return 'Data fetched'; // 返回数据 (Return data)
}
void main() async {
print('Fetching data...'); // 打印信息 (Print message)
String data = await fetchData(); // 等待数据 (Await data)
print(data); // 打印获取的数据 (Print fetched data)
}
7.2 使用 then (Using then)¶
fetchData().then((data) {
print(data); // 数据获取后执行 (Execute after data is fetched)
});
7.3 Stream¶
Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
yield i; // 生成序列中的下一个值 (Generate the next value in the sequence)
await Future.delayed(Duration(seconds: 1)); // 等待1秒 (Wait for 1 second)
}
}
void main() async {
await for (int value in countStream(5)) {
print('value: $value'); // 逐个处理 Stream 中的每个值 (Process each value in the Stream)
}
}
8. 异常处理 (Exception Handling)¶
try {
int result = 10 ~/ 0; // ~/ 是整除操作符 (~/ is the integer division operator)
print(result);
} catch (e) {
print('Caught an exception: $e'); // 捕获异常并打印 (Catch the exception and print it)
} finally {
print('This block is always executed'); // 最终块总是执行 (The finally block is always executed)
}
9. 泛型 (Generics)¶
9.1 泛型类 (Generic Class)¶
class Box<T> {
T value;
Box(this.value);
}
9.2 泛型函数 (Generic Function)¶
T getFirst<T>(List<T> items) {
return items[0]; // 返回列表中的第一个元素 (Return the first item in the list)
}
var firstInt = getFirst<int>([1, 2, 3]); // 使用泛型函数 (Using the generic function)
var firstString = getFirst<String>(['a', 'b', 'c']);
10. 扩展方法 (Extension Methods)¶
10.1 定义扩展方法 (Defining an Extension Method)¶
extension StringExtensions on String {
String toCapitalized() {
return this[0].toUpperCase() + this.substring(1); // 首字母大写 (Capitalize the first letter)
}
}
// 使用扩展方法 (Using an Extension Method)
void main() {
String text = 'hello';
print(text.toCapitalized()); // 输出: Hello (Output: Hello)
}
11. 常用库 (Common Libraries)¶
import 'dart:math'; // 数学函数和常用 (Math functions and constants)
import 'dart:convert'; // JSON 编码和解码 (JSON encoding and decoding)
import 'dart:io'; // 文件和网络 I/O (File and network I/O)
import 'dart:async'; // 异步编程 (Asynchronous programming)
import 'package:http/http.dart' as http; // HTTP 请求 (HTTP requests)
12. 注释 (Comments)¶
12.1 单行注释 (Single-line Comment)¶
// 这是一个单行注释 (This is a single-line comment)
var name = 'Xihai'; // 变量声明 (Variable declaration)
12.2 多行注释 (Multi-line Comment)¶
/*
这是一个多行注释
(This is a multi-line comment)
它可以跨越多行 (It can span multiple lines)
*/
var age = 30;
12.3 文档注释 (Documentation Comment)¶
/// 这是一个文档注释 (This is a documentation comment)
/// 用于类、方法或变量的文档生成 (Used for generating documentation for classes, methods, or variables)
class Person {
String name;
int age;
/// 构造函数 (Constructor)
Person(this.name, this.age);
/**
* 这是一个多行文档注释
* (This is a multi-line documentation comment)
* 用于提供详细的类或方法文档 (Used for providing detailed documentation for a class or method)
*/
void sayHello() {
print('Hello, my name is $name.');
}
}
13. 运算符 (Operators)¶
13.1 算术运算符 (Arithmetic Operators)¶
int a = 10;
int b = 5;
int sum = a + b; // 加法 (Addition)
int difference = a - b; // 减法 (Subtraction)
int product = a * b; // 乘法 (Multiplication)
double quotient = a / b; // 除法 (Division)
int remainder = a % b; // 取模 (Modulus)
int integerDivision = a ~/ b; // 整除 (Integer Division)
13.2 关系运算符 (Relational Operators)¶
bool isEqual = (a == b); // 等于 (Equal)
bool isNotEqual = (a != b); // 不等于 (Not equal)
bool isGreaterThan = (a > b); // 大于 (Greater than)
bool isLessThan = (a < b); // 小于 (Less than)
bool isGreaterThanOrEqual = (a >= b); // 大于等于 (Greater than or equal)
bool isLessThanOrEqual = (a <= b); // 小于等于 (Less than or equal)
13.3 逻辑运算符 (Logical Operators)¶
bool isTrue = true;
bool isFalse = false;
bool andResult = isTrue && isFalse; // 逻辑与 (Logical AND)
bool orResult = isTrue || isFalse; // 逻辑或 (Logical OR)
bool notResult = !isTrue; // 逻辑非 (Logical NOT)
13.4 位运算符 (Bitwise Operators)¶
int x = 5; // 0101 in binary
int y = 3; // 0011 in binary
int andResult = x & y; // 位与 (Bitwise AND) - 0001
int orResult = x | y; // 位或 (Bitwise OR) - 0111
int xorResult = x ^ y; // 位异或 (Bitwise XOR) - 0110
int notResult = ~x; // 位非 (Bitwise NOT) - 1010 (inverted bits)
int leftShift = x << 1; // 左移 (Left shift) - 1010 (10 in decimal)
int rightShift = x >> 1; // 右移 (Right shift) - 0010 (2 in decimal)
13.5 赋值运算符 (Assignment Operators)¶
int value = 10;
value += 5; // 相当于 value = value + 5 (Equivalent to value = value + 5)
value -= 3; // 相当于 value = value - 3 (Equivalent to value = value - 3)
value *= 2; // 相当于 value = value * 2 (Equivalent to value = value * 2)
value /= 2; // 相当于 value = value / 2 (Equivalent to value = value / 2)
value %= 3; // 相当于 value = value % 3 (Equivalent to value = value % 3)
value ~/= 2; // 相当于 value = value ~/ 2 (Equivalent to value = value ~/ 2)
13.6 条件运算符 (Conditional Operators)¶
String result = (age > 18) ? 'Adult' : 'Not an Adult'; // 三元运算符 (Ternary Operator)
String? name;
String displayName = name ?? 'Guest'; // 如果 name 为 null,则返回 'Guest' (Return 'Guest' if name is null)
13.7 类型测试运算符 (Type Test Operators)¶
if (name is String) {
print('Name is a string'); // 检查 name 是否为 String 类型 (Check if name is of type String)
}
if (age is! int) {
print('Age is not an integer'); // 检查 age 是否不是 int 类型 (Check if age is not of type int)
}
14. Null 安全 (Null Safety)¶
14.1 可空类型 (Nullable Types)¶
String? name; // name 可能为 null (name can be null)
14.2 非空断言操作符 (Null Assertion Operator)¶
String name = getName()!; // 确定 getName() 返回的值不为 null (Assert that the result of getName() is not null)
14.3 空条件操作符 (Null-aware Operators)¶
String? name;
String displayName = name ?? 'Guest'; // 如果 name 为 null,则返回 'Guest' (Return 'Guest' if name is null)
name?.toLowerCase(); // 如果 name 不为 null,则调用 toLowerCase() (Call toLowerCase() if name is not null)
15. Dart 与集合 (Dart and Collections)¶
15.1 列表 (Lists)¶
List<String> fruits = ['Apple', 'Banana', 'Orange']; // 定义一个字符串列表 (Define a list of strings)
fruits.add('Mango'); // 添加元素 (Add an element)
fruits.remove('Banana'); // 删除元素 (Remove an element)
fruits[0] = 'Grapes'; // 更新元素 (Update an element)
String firstFruit = fruits[0]; // 访问元素 (Access an element)
15.2 映射 (Maps)¶
Map<String, int> scores = {'Math': 95, 'English': 88}; // 定义一个映射 (Define a map)
scores['Science'] = 90; // 添加键值对 (Add a key-value pair)
scores.remove('English'); // 删除键值对 (Remove a key-value pair)
int mathScore = scores['Math']!; // 访问值 (Access a value)
15.3 集合 (Sets)¶
Set<String> colors = {'red', 'green', 'blue'}; // 定义一个集合 (Define a set)
colors.add('yellow'); // 添加元素 (Add an element)
colors.remove('green'); // 删除元素 (Remove an element)
bool containsRed = colors.contains('red'); // 检查集合是否包含某元素 (Check if the set contains an element)
16. 导入库 (Importing Libraries)¶
import 'dart:math'; // 导入 Dart 内置数学库 (Import Dart's built-in math library)
import 'package:http/http.dart' as http; // 导入第三方 HTTP 库 (Import a third-party HTTP library)
17. late
关键字 (The late
Keyword)¶
late
是 Dart 中的一个关键字,用于声明一个延迟初始化的变量。使用 late
声明的变量会在它首次被访问时才会进行初始化,而不是在声明时立即初始化。
late
is a keyword in Dart used to declare a lazily initialized variable. A variable declared with late
will only be initialized the first time it is accessed, rather than at the time of declaration.