类型和变量
- 一切是对象 -> 默认值null
-
Object
优于 dynamic
-
final
、const
、var
-
bool
不支持其他类型强制转换
- Symbol:
#varName
函数
[Type] funName ([[Type] param1[, …]]) {
codeBlock;
}
- 函数参数和返回类型可省略
-
=> expr;
可用于缩写{ return expr; }
- 命名参数:
//define
funName({type1: param1, type2: param2}) {}
//call
funName(param1: val1, param2: val2);
- 必选命名参数标记
@required
from meta.dart
- 匿名参数,可选参数放在
[]
中,放在参数列表最后:
//define
funName(type1 param1, type2 param2, [type3 param3]) {}
//call
funName(val1, val2);
([[Type] param1[, …]]) {
codeBlock;
};
操作符
-
~/
整除
-
is
is!
as
-
..
层叠操作符用来对一个对象进行连续多次操作
-
?.
允许操作对象为null
控制流
-
if
else
-
for
forEach()
for in
-
while
do-while
-
break
continue
-
switch
case
-
assert
测试环境抛AssertionError
异常
- 方法不需声明自己可能抛出的异常
-
Error
Exception
以及任何类型的对象都可以被抛出
- catch:
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
类
-
new
是可选的
- 抽象类
abstract
- 常量构造函数
var p = const ImmutablePoint(2, 2);
- 对象属性
runtimeType
用于发现对象类型,该属性类型是Type
- 默认构造函数、命名构造函数,构造函数不继承
- 继承:
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person does not have a default constructor;
// you must call super.fromJson(data).
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
Point.fromJson(Map json)
: x = json['x'],
y = json['y'] {
print('In Point.fromJson(): ($x, $y)');
}
class ImmutablePoint {
static final ImmutablePoint origin =
const ImmutablePoint(0, 0);
final num x, y;
const ImmutablePoint(this.x, this.y);
}
class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to
// the _ in front of its name.
static final Map _cache =
{};
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 msg) {
if (!mute) print(msg);
}
}
-
get
set
,也可以为抽象方法
- 抽象方法必须定义在抽象类,不需加
abstract
- 所有
class
自动生成一个同名的接口类,可以被其他类implements
- 部分运算符可重载,
==
和hashCode get
要一起重载
class Vector {
final int x, y;
Vector(this.x, this.y);
Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
}
- 重载
noSuchMethod()
可以避免NoSuchMethodError
抛出
- 枚举
enum Identifier {...}
,index
从0开始,Identifier.values
常量可用于遍历枚举的元素
-
mixin
用来声明一个mixin类型,扩展Object
,其他类型使用with
关键字实现mixin
- 使用
on
限制可以使用mixin的类型
mixin MusicalPerformer on Musician {
}
-
static
静态方法和成员
- 限制泛型参数类型
List
库
- 内建库
import 'dart:Xlib;'
- 一般库
import 'package:test/test.dart';
- 特殊用法:
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;
// Import only foo.
import 'package:lib1/lib1.dart' show foo;
// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;
import 'package:greetings/hello.dart' deferred as hello;
Future greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
异步
await lookUpVersion();
Future checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}
-
async
方法不会阻塞,async
方法返回Future
- 使用
try/catch/finally
处理await
里的错误和释放资源
-
await expression
里的表达式通常是Future
,如果不是也会被自动包装成Future
- 使用
async
和await for
处理流:
Future fun() async {
// ...
await for (var request in requestServer) {
handleRequest(request);
}
// ...
}
- 下面代码
expression
必须是Stream类型,使用break/return
停止监听stream
await for (varOrType identifier in expression) {
// Executes each time the stream emits a value.
}
生成器
- 关键字
sync*
, yield
- 同步生成器:
Iterable
Iterable naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
Stream asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
Iterable naturalsDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* naturalsDownFrom(n - 1);
}
}
其他
class WannabeFunction {
call(String a, String b, String c) => '$a $b $c!';
}
main() {
var wf = new WannabeFunction();
var out = wf("Hi","there,","gang");
print('$out');
}
-
dart:isolate
:所有的dart代码运行在isolates中,不是线程,isolate内存对战独立,他的状态不能从外部访问
-
typedef
只能用于方法
typedef Compare = int Function(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}