相对于java dart 还有一些非常重要的关键字,他们各有各特点,但是如果你不理解他们的用法,看代码的话肯定是一点也看不懂的,先来说一下async 这个我们之前看到过的
async await
应用场景 异步 返回类型 Future
Future<int> test_async() async {
Future<int> future = Future.delayed(Duration(seconds: 2),()=>1);
return future;
}
如果我们想要结果的话则需要配合await 使用
Future<int> test_async() async {
int future =await Future.delayed(Duration(seconds: 2),()=>1);
printString(future);
return future;
}
}
sync* yield
应用场景 同步 返回类型Iterable<T>
void test(){
test_sync([4,7,12,15,22]).forEach((element) {printString(element);});
}
Iterable<int> test_sync(List<int> array) sync* {
for (int i = 0; i < array.length; i++) {
yield array[i];
}
}
结果
I/flutter ( 7129): tian.shm =4
I/flutter ( 7129): tian.shm =7
I/flutter ( 7129): tian.shm =12
I/flutter ( 7129): tian.shm =15
I/flutter ( 7129): tian.shm =22
sync* yield*
应用场景 同步 返回类型Iterable<T> ,相对于async* yield ,yield* 后面必须是一个Iterable<T> ,yield 则必须是T ,
test() {
test_yield().forEach((element) {printString(element);});
}
Iterable<int> test_yield() sync*{
yield* test_sync([4,7,12,15,22]).map((e){
return e*e;
});
}
Iterable<int> test_sync(List<int> array) sync* {
for (int i = 0; i < array.length; i++) {
yield array[i];
}
}
结果
I/flutter ( 7129): tian.shm =4
I/flutter ( 7129): tian.shm =7
I/flutter ( 7129): tian.shm =12
I/flutter ( 7129): tian.shm =15
I/flutter ( 7129): tian.shm =22
async* yield
应用场景 异步 返回类型 Stream<T> yield 后面必须是 T
test() {
test_async([2, 15,42,53,64,73,77,99]).interval(Duration(seconds: 1)).listen((event) {printString('listen1:$event');});
}
Stream<int> test_async(List<int> array) async*{
for(int i=0;i<array.length;i++){
yield array[i];
}
}
结果
I/flutter ( 7129): tian.shm =listen1:2
I/flutter ( 7129): tian.shm =listen1:15
I/flutter ( 7129): tian.shm =listen1:42
I/flutter ( 7129): tian.shm =listen1:53
I/flutter ( 7129): tian.shm =listen1:64
I/flutter ( 7129): tian.shm =listen1:73
I/flutter ( 7129): tian.shm =listen1:77
I/flutter ( 7129): tian.shm =listen1:99
async* yield*
应用场景 异步 返回类型 Stream<T> yield* 后面必须是Stream<T>
test() {
test_async_1().listen((event) {printString('listen2:$event');});
}
Stream<int> test_async(List<int> array) async*{
for(int i=0;i<array.length;i++){
yield array[i];
}
}
Stream<int> test_async_1() async*{
yield* test_async([2, 15,42,53,64,73,77,99]).map((event) => event*event);
}
结果
I/flutter ( 7129): tian.shm =listen2:4
I/flutter ( 7129): tian.shm =listen2:225
I/flutter ( 7129): tian.shm =listen2:1764
I/flutter ( 7129): tian.shm =listen2:2809
I/flutter ( 7129): tian.shm =listen2:4096
I/flutter ( 7129): tian.shm =listen2:5329
I/flutter ( 7129): tian.shm =listen2:5929
I/flutter ( 7129): tian.shm =listen2:9801
我学习flutter的整个过程都记录在里面了
https://www.jianshu.com/c/36554cb4c804
最后附上demo 地址