当前位置: 首页 > news >正文

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(); // 使用扩展方法

四、重要概念

  1. 一切皆对象:Dart中所有值都是对象,包括数字、函数和null

  2. 强类型但支持类型推断:使用var声明变量时,类型在编译时确定

  3. 单线程模型:Dart使用事件循环和异步编程模型处理并发

  4. isolate实现真正并发:通过isolate实现多线程,内存不共享

  5. JIT和AOT编译:开发时使用JIT实现热重载,发布时使用AOT编译为原生代码

  6. 树摇优化:只包含实际使用的代码,减小应用体积

  7. 响应式编程支持:与Flutter框架完美结合,支持声明式UI编程

五、最佳实践

  1. 优先使用finalconst声明不可变变量

  2. 对公共API使用显式类型声明

  3. 使用??操作符提供默认值

  4. 使用级联操作符(..)简化对象配置

  5. 对异步代码优先使用async/await而非直接使用FutureAPI

  6. 使用集合字面量而非构造函数初始化集合

  7. 为复杂参数使用命名参数

  8. 合理使用late关键字处理延迟初始化

Dart语言特别适合构建跨平台移动应用(通过Flutter框架),其语法简洁但功能强大,结合了现代语言的诸多特性,同时保持了高性能和良好的开发体验。

http://www.dtcms.com/a/318373.html

相关文章:

  • 数据结构—队列和栈
  • openGauss单实例安装
  • YOLOv11改进:集成FocusedLinearAttention与C2PSA注意力机制实现性能提升
  • Redis使用的常见问题及初步认识
  • PLC学习之路-数据类型与地址表示-(二)
  • WinXP配置一键还原的方法
  • 【golang面试题】Golang递归函数完全指南:从入门到性能优化
  • 五十二、【Linux系统shell脚本】正则表达式演示
  • 202506 电子学会青少年等级考试机器人五级实际操作真题
  • 数据结构:栈、队列
  • C语言的数组与字符串练习题1
  • 18650电池组PACK自动化生产线:高效与品质的融合
  • 动物AI识别摄像头语音对讲功能
  • 大模型客户端工具如Cherry Studio,Cursor 配置mcp服务,容易踩的坑,总结
  • RPC框架之Kitex
  • 云手机和云真机之间存在的不同之处有什么?
  • [Oracle] LPAD()和RPAD()函数
  • Python实现电商商品数据可视化分析系统开发实践
  • 一、Istio基础学习
  • 自定义报表调研
  • 居家养老场景下摔倒识别准确率提升 29%:陌讯动态姿态建模算法实战解析
  • JuiceFS存储
  • C++实现线程池(5)计划线程池
  • Redis知识学习
  • 深度解析:AI如何重塑供应链?从被动响应到预测性防御的三大核心实践
  • (Python)待办事项升级网页版(html)(Python项目)
  • 未解决|TransmittableThreadLocal 怎么用| 阿里线程池工具避免手动在传递MDC traceId
  • 数字取证和网络安全:了解两者的交叉点和重要性
  • 《爬虫实战指南:轻松获取店铺详情,开启数据挖掘之旅》
  • 【网络基础】计算机网络发展背景及传输数据过程介绍