Flutter和Dart是异步的,使用Dart的Futures可以管理IO,不用担心线程死锁等问题,但是如何在使用Widget时也使用异步操作呢?
Flutter提供了FutureBuilder来进行处理,FutureBuilder可以很容易的得到当前Widget的状态,并选择在加载数据时显示的内容.以及在可以使用时显示的内容.
首先给FutureBuilder设置future一个网络请求,builder可以获取到当前的操作是那种状态,比如已完成.根据不同的状态来显示不同的内容.
import 'package:flutter/material.dart';
import 'dart:io';
class GoogleFutureBuilder extends StatelessWidget {
@override
Widget build(BuildContext context) {
var httpClient = new HttpClient();
Widget waiting = Column(
children: <Widget>[
Text('waiting'),
Icon(Icons.cloud_download),
],
);
Widget active = Column(
children: <Widget>[
Text('active'),
Icon(Icons.access_time),
],
);
Widget error = Column(
children: <Widget>[
Text('error'),
Icon(Icons.error),
],
);
Widget done = Column(
children: <Widget>[
Text('done'),
Icon(Icons.done),
],
);
Widget none = Column(
children: <Widget>[
Text('none'),
Icon(Icons.filter_none),
],
);
return FutureBuilder(
future: httpClient.getUrl(Uri.parse('http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9')),
builder: (context, snap) {
if (snap.connectionState == ConnectionState.done) {
if (snap.hasError) {
return error;
}
return done;
} else if (snap.connectionState == ConnectionState.active) {
return active;
} else if (snap.connectionState == ConnectionState.waiting) {
return waiting;
} else if (snap.connectionState == ConnectionState.none) {
return none;
}
},
);
}
}