Flutter 異步編程

定時(shí)器簡(jiǎn)要使用
import 'dart:async';
void main(){
  print('開始定時(shí)器');
  Timer timer = new Timer(const Duration(seconds: 3 ),(){
      print('延遲三秒執(zhí)行...');
  });
  // 結(jié)束 timer.cancel
  print('結(jié)束定時(shí)器');

  //  開始定時(shí)器
  //  結(jié)束定時(shí)器
  //  延遲三秒執(zhí)行...
}

/// dart是單線程模型...
async使用
import 'dart:async';
void main(){
  printNews();
  methodOne();
}

void printNews() async{
  String news = await fetchInfo();
  print(news);
}

void methodOne(){
  print('methodOne 執(zhí)行任務(wù)');
}

Future fetchInfo(){
  Stream stream = new Stream.periodic(const Duration(seconds: 3),(T) => "goods news");
  return stream.first;
}

// methodOne 執(zhí)行任務(wù)
// ......等待3秒種
// goods news
// Process finished with exit code 0
異步查看
void main(){
  print('t1: '+ DateTime.now().toString());
  testAsync();
  print('t2: '+ DateTime.now().toString());
}

void testAsync() async {
  int result = await Future.delayed(Duration(seconds: 3),(){
    return Future.value(200);
  });
  print('t3:' + DateTime.now().toString());
  print(result);
}

//t1: 2019-04-09 23:21:27.741782
//t2: 2019-04-09 23:21:27.753891
//等待3秒
//t3:2019-04-09 23:21:30.764490
//200

在Future結(jié)束的時(shí)候我們需要進(jìn)行一系列的操作,then().catchError() 模式
try-catch, try-catch有個(gè)finally代碼塊,而future.whenComplete 類似于finally

void main(){
  var random = new Random(47);
  Future.delayed(Duration(seconds: 3),(){
    if(random.nextBool()){
      return 100;
    }else {
      throw 'boom';
    }
  }).then(print).catchError(print).whenComplete((){
    print('done');
  });

// 延遲3秒
//  100
//  done
}

Time設(shè)置超時(shí)

void main(){
  Future.delayed(Duration(seconds: 3),(){
    return 1;
  }).timeout(Duration(seconds: 2)).then(print)
      .catchError(print);
  // TimeoutException after 0:00:02.000000: Future not completed
  // Process finished with exit code 0
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容