生成器
通過在函數(shù)上添加關(guān)鍵字 sync*/async*
并在函數(shù)中使用yield
關(guān)鍵字來傳遞值悯衬,可以生成一連串的值酌心。
- 通過使用
sync*
關(guān)鍵字并返回Iterable
對象桩砰,返回一個同步生成器
Iterable<int> generate(int n) sync* {
while(n<10) {
yield n;
}
}
- 通過使用
async*
關(guān)鍵字并返回Stream
對象打却,返回一個異步生成器
Stream<int> generate(int n) async* {
while(n<10) {
yield n;
}
}
如果需要通過遞歸調(diào)用施掏,可以使用 yield*
來提升執(zhí)行性能。
Iterable<int> generate(int n) sync* {
while(n<10){
yield n;
yield* generate(n-1);
}
}
可調(diào)用類
通過實現(xiàn)call()
函數(shù)來實現(xiàn)通過函數(shù)的方式來使用類的實例谐丢;所有的類都可以定義一個call()
的函數(shù)爽航,這個函數(shù)和普通的函數(shù)一樣,可以定義返回值和參數(shù)乾忱。
class Test{
String call(String a,String b, String c) => 'a=${a},b=>$, c=>${c}';
}
void mian(){
var test = Test();
print(test('hello','dart','call')); // a=>hello,b=>dart,c=>call
}
隔離區(qū)
在Dart中历极,沒有線程的概念窄瘟,而是通過isolate
代替了線程,所有的Dart代碼都是運行在一個isolate
中趟卸。isolate
可以理解為一個單獨的進(jìn)程(并不是蹄葱,只是為了類比),每個isolate
都有自己的堆內(nèi)存锄列,其他isolate
都無法訪問图云;每個isolate
都有一個執(zhí)行線程。
isolate之間的通信:
// 創(chuàng)建一個消息接收器
ReceivePort rvp = ReceivePort();
// 創(chuàng)建一個新的isolate
Isolate.spvn(isoLateNew, rvp.sendPort);
// 接收消息
rvp.listen((message){
if(message is SendPort) {
message.send('hello, connected');
}else{
print(message);
}
})
void isolateNew(SendPort sendPort) {
// 創(chuàng)建消息接收器
ReceivePort rvp = ReceivePort();
// 發(fā)送自身的消息發(fā)送器
sendPort.send(rvp.sendPort);
// 發(fā)送消息
sendPort.send('hello,this is isolateNew, connecting');
// 監(jiān)聽消息
rvp.listen((message){
print(message);
})
}
Typedefs
使用關(guān)鍵字 typedef
來給某一類型定義類型別名邻邮,來簡化復(fù)雜類型竣况。
typedef IntList = List<int>;
IntList li = [1,2,3];
類型別名也可以參數(shù)化類型
typedef ListMapper<T> = Map<T,List<T>>;
Map<String,List<String>> m1 = {};
// m1 & m2 效果一樣
ListMap<String> m2 = {};
元數(shù)據(jù)
使用元數(shù)據(jù)可以為代碼增加一些額外的信息。元數(shù)據(jù)注解以@
開頭筒严,其后緊跟一個編譯時常量丹泉,或者調(diào)用一個常量構(gòu)造函數(shù)情萤。
class Todo {
final String who;
final String what;
const Todo(this.who, this.what);
}
@Todo('seph', 'Implement this function late')
void doSomething() {
}
元數(shù)據(jù)可以在 library
、class
摹恨、typedef
筋岛、type parameter
、 constructor
晒哄、factory
睁宰、function
、field
寝凌、parameter
或者 variable
聲明之前使用勋陪,也可以在 import
或 export
之前使用×蚶迹可使用反射在運行時獲取元數(shù)據(jù)信息诅愚。