Flutter进阶篇(4)-- Flutter的Future异步详解
Flutter之FutureBuilder的学习和使用
Future
Flutter的异步操作。
future里面有几个函数:
then:异步操作逻辑在这里写。
whenComplete:异步完成时的回调。
catchError:捕获异常或者异步出错时的回调。
Future asyncDemo() async{
Future<Null> future = new Future(() => null);
await future.then((_){
print("then");
}).then((){
print("whenComplete");
}).catchError((_){
print("catchError");
});
}
FutureBuilder
Flutter中的异步模型,基于与Future交互的最新快照来构建自身的widget。
const FutureBuilder({
Key key,
this.future,
this.initialData,
@required this.builder
}) : assert(builder != null),
super(key: key);
- FutureBuilder中包含Future和builder。
- Future通过异步操作来获取数据,builder中传入上下文context和异步快照AsyncSnapshot。
- AsyncSnapshot中包含ConnectionState、data等。builder根据快照的状态返回不同的widget。