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修饰的方法内才有效
相关推荐
D-海漠13 分钟前
Modbus_TCP_V4 客户端
网络
虚!!!看代码1 小时前
【Sentinel学习】
网络·sentinel
liulilittle1 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
网硕互联的小客服1 小时前
服务器如何配置防火墙规则以阻止恶意流量和DDoS攻击?
服务器·网络·ddos
Qiq9221 小时前
怎么分析内网ipv6和ipv4流量占比?
网络
数通Dinner1 小时前
P/A初始化协商
网络
网安小白的进阶之路1 小时前
A模块 系统与网络安全 第三门课 网络通信原理-3
网络·windows·安全·web安全·系统安全
HumanRisk1 小时前
HumanRisk-自动化安全意识与合规教育平台方案
网络·安全·web安全·网络安全意识教育
网络小白不怕黑2 小时前
华为设备 QoS 流分类与流标记深度解析及实验脚本
网络·华为