声明:var final const。支持自动推断类型,但类型一直固定。未初始化的值为 null
Final vs const: const 编译时确定,final 运行时确定
基本类型:num int double String bool List Set Map
- int.parse('1'); // 1 1.toString()
- 带变量的字符串:${expression}
- 字符串连接:"字符串1" "字符串2"
"字符串3";
用加号也行 - 多行字符串
'''
这是第一行字符串。
这是第二行字符串。
''' - enum Color { red, green, blue } Color.blue Color.blue.index
级联调用:a...b=1;...c.d() 等价于 a.b=1; a.c.d()
算数运算符:/除 ~/除法取整
类型运算符:as is is!
条件运算符:x ?? y 等价于 x ? x : y
List 类型:list.add('x') list.insert(2, 'x') list.remove('x') list.sort() list.sort((a, b) => a < b ? 1 : -1) list.indexOf('x') list.contains('x')
new 是可选的 List a = new List(); ✅ List a = List();✅
Set 类型:set.add('x') set.addAll(['x', 'y', 'z']) set.remove('x') set.clear() set.contains('x') for(var x in set)
Map 类型:map["k1"]="v1" map.remove("k1") map.clear() map.length map.foreach((k, v) {})
忽略参数定义顺序的函数传参:定义:void enableFlags({bool bold, bool hidden}) {} enableFlags(hidden: true, bold: false);
可选参数:void fun(int a, [int b=1, int c=2]){}
闭包函数:(a, b) {return a>b} 闭包函数可以做闭包。箭头函数:(a, b)=>a>b
类:_x私有属性 this.y✅ y✅(在没有歧义的情况下) 参数初始化 Point(int x, int y) : this.x = x, this.y = y {} Point(this.x, this.y);
命名构造方法(预制构造方法)Point.origin() {x = 0;y = 0;} new Point.origin()
工厂模式构造方法:factory X(String type){if(type=='type1') return x;if(type=='type1') return y;}一般要搭配命名构造方法使用
extends implements
运算符重载 bool operator <(Point v) => x < v.x && y < v.y;
mixin 实现多继承:被混入的类 mixin X {...} 继承 class A extends Y with X, Z {...}
异常可以直接 throw "string" 或 throw Exception("xxx")
捕获异常:try {...} on AException {...} on BException {...} on Exception catch (e) {...} catch (e) {...}
重新抛出异常:rethrow
Finally
异步处理 Future=Promise async/await
异步数据序列 Stream await for (数据类型 变量 in stream类型变量) {// 处理数据}