Flutter 三点二:Dart 异步 async 和 await

async 和 await

  • Future 链式调用 更清晰
  • 异步操作依赖关系比较复杂 可使用async await
  • async await 调用逻辑更清晰
  • async await 异常处理 try{}catch(){} 即可
  • async 修饰的方法 总是返回Future对象 不会阻塞主线程
  • await 关键字只有在async修饰的方法内才有效
  • 都是把事件交给 EventLoop
登录流程Future写法
复制代码
void main() {
    Future.value(["username","password"])
        .then((value){
        login(value[0],value[1]);
        print("${DateTime.now().millisecondsSinceEpoch} >> 登录中...");
        sleep(Duration(seconds: 5));
        return '{"id": 10001,"name": "John","classGrade": "三年二班","birthday": "2005-12-12 12:12:12", "age": 30}';})
        .then((value){
        return value;
    })
        .then((value){
        print("${DateTime.now().millisecondsSinceEpoch} >> "+value);  //json
        var json = jsonDecode(value);
        int id = json['id'];
        getUserInfo(id);
        print("${DateTime.now().millisecondsSinceEpoch} >> 获取用户信息...");
        sleep(Duration(seconds: 5));
        return "成功,缓存数据,跳转首页";
    })
        .catchError((value){})
        .whenComplete((){
        print("登录流程结束!");
    });
}

login(String username,String password){
    print("${DateTime.now().millisecondsSinceEpoch} >> ${username}请求登录!");
}
getUserInfo(int id){
    print("${DateTime.now().millisecondsSinceEpoch} >> ${id}获取用户信息!");
}

运行结果

复制代码
1703727827384 >> username请求登录!
1703727827384 >> 登录中...
1703727832400 >> {"id": 10001,"name": "John","classGrade": "三年二班","birthday": "2005-12-12 12:12:12", "age": 30}
1703727832418 >> 10001获取用户信息!
1703727832418 >> 获取用户信息...
登录流程结束!
async/await 写法
复制代码
import 'dart:convert';
import 'dart:io';

void main() async{
    var loginResult = await login("aaa", "123");
    var userInfo = await getUserInfo(loginResult);
    print(userInfo);
}

Future<String> login(String username,String password){
    print("${DateTime.now().millisecondsSinceEpoch} >> ${username}请求登录!");
    return  Future.value([username,password])
        .then((value){
        print("${DateTime.now().millisecondsSinceEpoch} >> 登录中...");
        sleep(Duration(seconds: 5));
        return '{"id": 10001,"name": "John","classGrade": "三年二班","birthday": "2005-12-12 12:12:12", "age": 30}';})
        .then((value){
        return value;
    });
}
Future<String> getUserInfo(String value){
    return Future((){
        print("${DateTime.now().millisecondsSinceEpoch} >> "+value);  //json
        var json = jsonDecode(value);
        print("${DateTime.now().millisecondsSinceEpoch} >> 获取用户信息...");
        sleep(Duration(seconds: 5));
        return "成功,缓存数据,跳转首页";
    });
}

请求结果

复制代码
1703727905612 >> aaa请求登录!
1703727905617 >> 登录中...   //5s等待返回结果
1703727910642 >> {"id": 10001,"name": "John","classGrade": "三年二班","birthday": "2005-12-12 12:12:12", "age": 30}
1703727910660 >> 获取用户信息...    //5s等待
1703727915670 >> 成功,缓存数据,跳转首页   
async 修饰的方法 总是返回Future对象 不会阻塞主线程
复制代码
import 'dart:convert';
import 'dart:io';

void main(){
   var login = startLogin();
   print("login.runtimeType>>${login.runtimeType}");
}

startLogin() async{
    var loginResult = await login("aaa", "123");
    var userInfo = await getUserInfo(loginResult);
    print("${DateTime.now().millisecondsSinceEpoch} >> "+userInfo);
}

Future<String> login(String username,String password){
    return  Future.value([username,password])
        .then((value){
        print("${DateTime.now().millisecondsSinceEpoch} >> 登录中...");
        sleep(Duration(seconds: 5));
        return '{"id": 10001,"name": "John","classGrade": "三年二班","birthday": "2005-12-12 12:12:12", "age": 30}';})
        .then((value){
        return value;
    });
}
Future<String> getUserInfo(String value){
    return Future((){
        print("${DateTime.now().millisecondsSinceEpoch} >> "+value);  //json
        var json = jsonDecode(value);
        print("${DateTime.now().millisecondsSinceEpoch} >> 获取用户信息...");
        sleep(Duration(seconds: 5));
        return "成功,缓存数据,跳转首页";
    });
}

结果:

复制代码
login.runtimeType>>Future<dynamic>  //类型是Future
await 关键字只有在async修饰的方法内才有效
相关推荐
被摘下的星星几秒前
以太网技术
服务器·网络
24zhgjx-lxq1 小时前
OSPF的网络类型:NBMA和P2MP
网络·智能路由器·hcip·ensp·ospf
Johnstons1 小时前
丢包率不高但应用仍然卡顿?一次基于 tcpdump +RTT抽样的网络性能排障实战
网络·wireshark·php·tcpdump
IpdataCloud1 小时前
IP查询高精度怎么选?8个指标判断是否适合你
网络·网络协议·tcp/ip
聊点儿技术2 小时前
IP风险等级评估是什么?跨境电商业务场景全解析
网络·网络协议·tcp/ip
herinspace2 小时前
如何解决管家婆辉煌零售POS中显示的原价和售价不一致?
网络·人工智能·学习·excel·语音识别·零售
JS_SWKJ2 小时前
多网闸级联部署避坑指南:安全与性能如何兼得?
网络·安全
Lyyaoo.2 小时前
【JAVA网络面经】网络模型(OSI+TCP/IP)
网络
路溪非溪3 小时前
网络运输层:TCP协议详解(一)
网络·网络协议·tcp/ip
汽车仪器仪表相关领域3 小时前
Kvaser Leaf Light HS v2 M12:5 针 M12 NMEA 2000 接口,海事与工业 CAN 总线测试的防水耐用之选
大数据·网络·人工智能·功能测试·安全性测试