flutter-异步支持

Future用来异步操作。
1.延时发送Future.then()

Future.delayed(new Duration(seconds: 1),(){
    return "hello world";
  }).then((value) => print(value));

2.异常捕获Future.catchError

Future.delayed(new Duration(seconds: 1),(){
    // return "hello world";
    throw AssertionError("error");
  }).then((value) => print(value))
  .catchError((e)=>print(e));

捕获异常的另一种表现方式

Future.delayed(new Duration(seconds: 1),(){
    // return "hello world";
    throw AssertionError("error");
  }).then((value) => print(value),onError: (e){print(e);});

3.Future.whenComplete异步操作执行完毕执行的操作,比如在这里处理弹窗。

Future.delayed(new Duration(seconds: 1),(){
    // return "hello world";
    throw AssertionError("error");
  }).then((value) => print(value))
  .catchError((e)=>print(e)).whenComplete(() => print("弹个弹窗"));

4.Future.wait用来等待多个异步任务,执行完毕之后,比如多个网络请求,再执行then中的代码。

Future.wait([Future.delayed(new Duration(seconds: 2),(){return "hello";}),
    Future.delayed(new Duration(seconds: 3),(){return "world";})])
      .then((value) => print(value));

async/wait;
使用async来表示异步调用函数是异步的,
wait必须写在async的包含体中

task() async {
   try{
    String id = await login("alice","******");
    String userInfo = await getUserInfo(id);
    await saveUserInfo(userInfo);
    //执行接下来的操作   
   } catch(e){
    //错误处理   
    print(e);   
   }  
}

Stream也可以用来接收异步信息,一般用来网络下载和文件读取。

Stream.fromFutures([Future.delayed(new Duration(seconds: 1),(){return "hello1";}),
    Future.delayed(new Duration(seconds: 2),(){throw AssertionError("Error");}),
  Future.delayed(new Duration(seconds: 3),(){return "hello3";})])
  .listen((event) {print(event);},onError: (e){print(e);},onDone: (){
    print("弹出提示");

你可能感兴趣的:(flutter-异步支持)