Flutter 异步

以aws_sns_api插件为例

import 'package:flutter/material.dart';
import 'package:aws_sns_api/sns-2010-03-31.dart';
import 'dart:async';
void main() {
  // aws sns
  createEndpointArn().then((value) => print('get endpointArn ===== $value'));
  runApp(MyApp());
}

Future<String> createEndpointArn() async {
  var endpointArn;
  try{
    final service = SNS(region: 'eu-west-1');
    await service.addPermission(awsAccountId: null, actionName: null, label: null, topicArn: null);
    CreatePlatformApplicationResponse createPAResp = await service.createPlatformApplication(attributes: null, name: null, platform: null);
    String platformApplicationArn = createPAResp.platformApplicationArn;
    CreateEndpointResponse createEResp = await service.createPlatformEndpoint(platformApplicationArn: platformApplicationArn, token: null);
    endpointArn = createEResp.endpointArn;
  }catch(e) {
    print('amazon sns error ==== $e');
  }
  return endpointArn;
}

class MyApp extends StatelessWidget {...}

对Future的理解

表示一个异步操作的最终完成(或失败)及其结果值的表示,Future的所有API的返回值仍然是一个Future对象,可以方便的进行链式调用。Future是一种抽象,其表示这个对象封装的数据是未来的。我们可以通过执行Future对象的then方法来设置回调函数(如果要获取值,依赖async函数的返回值,例如前面例子中的return endpointArn;)。

异步函数的返回值会作为Future对象设置回调的参数,因此在编写异步async函数时,开发者不需要再考虑数据的处理问题,将获取的数据直接返回即可。Future这种异步编程的方式使代码的结构性更强,并且,如果有多个异步任务有依赖,使用Future可以非常方便地进行依赖关系处理

async用来表示函数是异步的,定义的函数会返回一个Future对象。使用then添加回调函数

await 后面是一个Future, 表示等待该异步任务完成。await必须在async函数内部。

posted @ 2020-09-02 13:46  yxg889  阅读(189)  评论(0编辑  收藏  举报