Dart语言语法与技术重点
Dart语言语法与技术重点总结
一、基础语法
1. 变量与常量
var name = 'Dart'; // 类型推断
String name = 'Dart'; // 显式类型声明
final name = 'Dart'; // 运行时常量
const pi = 3.14; // 编译时常量
dynamic dynamicVar = '可以改变类型'; // 动态类型
2. 数据类型
- 基本类型:int, double, bool, String
- 集合类型:List, Set, Map
- 特殊类型:Runes(用于字符串Unicode), Symbol
List<int> numbers = [1, 2, 3]; // 泛型列表
Set<String> names = {'Alice', 'Bob'}; // 集合
Map<String, int> ages = {'Alice': 25, 'Bob': 30}; // 映射
3. 运算符
- 空安全运算符:
var name = nullableName ?? 'default'; // 空合并 var length = name?.length; // 安全调用
- 级联运算符:
..
(允许对同一对象执行多个操作)var paint = Paint()..color = Colors.black..strokeWidth = 5.0;
4. 控制流程
// if-else
if (isRaining) {// ...
} else if (isSnowing) {// ...
} else {// ...
}// for循环
for (var i = 0; i < 5; i++) {print(i);
}// for-in循环
for (var number in numbers) {print(number);
}// while循环
while (!isDone) {// ...
}// switch-case
switch (command) {case 'START':start();break;case 'STOP':stop();break;default:unknown();
}
二、函数与类
1. 函数
// 常规函数
int add(int a, int b) {return a + b;
}// 箭头函数(单行)
int add(int a, int b) => a + b;// 可选参数(位置参数)
String say(String from, [String? msg]) {// ...
}// 可选命名参数
void enableFlags({bool bold = false, bool hidden = false}) {// ...
}// 匿名函数
var list = ['a', 'b', 'c'];
list.forEach((item) {print(item);
});
2. 类与对象
class Point {// 实例变量double x, y;// 构造函数Point(this.x, this.y);// 命名构造函数Point.origin() : x = 0, y = 0;// 方法double distanceTo(Point other) {var dx = x - other.x;var dy = y - other.y;return sqrt(dx * dx + dy * dy);}// Getterdouble get magnitude => sqrt(x * x + y * y);// Setterset magnitude(double value) {var ratio = value / magnitude;x *= ratio;y *= ratio;}
}// 使用
var p1 = Point(10, 20);
var p2 = Point.origin();
3. 继承与接口
// 继承
class Animal {void eat() => print('Eating');
}class Dog extends Animal {void bark() => print('Barking');
}// 接口实现
abstract class Shape {double area();
}class Circle implements Shape {final double radius;Circle(this.radius); double area() => pi * radius * radius;
}
4. Mixin
mixin Musical {void playMusic() => print('Playing music');
}class Performer {void perform() => print('Performing');
}class Musician extends Performer with Musical {// 现在有perform()和playMusic()方法
}
三、高级特性
1. 空安全
int? nullableInt = null; // 可空类型
int nonNullableInt = 0; // 非空类型// 空断言操作符
int value = nullableInt!; // 开发者确保不为null// 延迟初始化
late String description;
2. 异步编程
// Future
Future<String> fetchUserOrder() {return Future.delayed(Duration(seconds: 2), () => 'Large Latte');
}// async/await
Future<void> printOrderMessage() async {try {var order = await fetchUserOrder();print('Order is: $order');} catch (err) {print('Error: $err');}
}// Stream
Stream<int> countStream(int to) async* {for (int i = 1; i <= to; i++) {yield i;}
}
3. 泛型
class Box<T> {final T value;Box(this.value);T getValue() => value;
}var intBox = Box<int>(42);
var stringBox = Box<String>('Hello');
4. 扩展方法
extension NumberParsing on String {int parseInt() {return int.parse(this);}
}'42'.parseInt(); // 使用扩展方法
四、重要概念
-
一切皆对象:Dart中所有值都是对象,包括数字、函数和null
-
强类型但支持类型推断:使用
var
声明变量时,类型在编译时确定 -
单线程模型:Dart使用事件循环和异步编程模型处理并发
-
isolate实现真正并发:通过isolate实现多线程,内存不共享
-
JIT和AOT编译:开发时使用JIT实现热重载,发布时使用AOT编译为原生代码
-
树摇优化:只包含实际使用的代码,减小应用体积
-
响应式编程支持:与Flutter框架完美结合,支持声明式UI编程
五、最佳实践
-
优先使用
final
和const
声明不可变变量 -
对公共API使用显式类型声明
-
使用
??
操作符提供默认值 -
使用级联操作符(
..
)简化对象配置 -
对异步代码优先使用
async/await
而非直接使用Future
API -
使用集合字面量而非构造函数初始化集合
-
为复杂参数使用命名参数
-
合理使用
late
关键字处理延迟初始化
Dart语言特别适合构建跨平台移动应用(通过Flutter框架),其语法简洁但功能强大,结合了现代语言的诸多特性,同时保持了高性能和良好的开发体验。