Flutter开发圈

Flutter-Future 异步支持

2020-08-10  本文已影响0人  爱运动的年轻人

题记

忙是治愈一切的良药

人只要忙起来就不会胡思乱想

也不会沉迷过往

当一个人有目的、有规划的忙

他满满就会明白

闲人是非多,一忙解千愁

image

异步支持

Dart类库有很多返回Future的函数, 那么这些我们叫它异步函数。通常都会在一些耗时操作之后返回 。如网络请求,本地数据读取等等

Future

用来处理异步操作,异步处理成功了就执行成功的操作,异步处理失败了就捕获错误或者停止后续操作。一个Future只会对应一个结果,要么成功,要么失败(Future所有的API返回值都是一个Future对象,方便你链式调用)

Future.then()

我们使用Future.delayed来写一个延时任务(模拟一个网络请求吧)。这里延迟2秒 然后返回'success' 然后经过t hen() 打印返回值

Future.delayed(new Duration(seconds: 2),(){ 
        return "success"; }
    ).then((data){   
            print(data); 
    }
    );

Future.whenComplete

在一定情景下, 我们会在请求失败或者成功的时候 都会做处理。如网络请求开是前会弹出加载图 成功后 关闭加载图

eg:

Future.delayed(new Duration(seconds: 2),(){
   //return "hello!";
   throw AssertionError("Error");
}).then((data){
   //执行成功会走到这里 
   print(data);
}).catchError((e){
   //执行失败会走到这里   
   print(e);
}).whenComplete((){
   //无论成功或失败都会走到这里
});

Future.catchError

在异步任务中抛出了一个异常, t hen的回掉不会执行 ,而是执行catchError, 但是并不是只有这个才能捕获错误 ,t hen 方法还有个onError参数, 也是可以捕获错误的

eg:

Future.delayed(new Duration(seconds: 2), () {
    //return "hi";
    throw AssertionError("Error");
}).then((data) {
    print("success");
}, onError: (e) {
    print(e);
});

Async/await

代码中有大量的异步逻辑 这时候可以用Async/await 控制代码块的代码是按顺序执行的

eg:

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

猜你喜欢

热点阅读