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
函数内部。
但行好事,莫问前程