Flutter 异步编程

定时器简要使用
import 'dart:async';
void main(){
  print('开始定时器');
  Timer timer = new Timer(const Duration(seconds: 3 ),(){
      print('延迟三秒执行...');
  });
  // 结束 timer.cancel
  print('结束定时器');

  //  开始定时器
  //  结束定时器
  //  延迟三秒执行...
}

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

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

void methodOne(){
  print('methodOne 执行任务');
}

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

// methodOne 执行任务
// ......等待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结束的时候我们需要进行一系列的操作,then().catchError() 模式
try-catch, try-catch有个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设置超时

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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。