Flutter和Dart是异步的,使用Dart的Futures可以管理IO,不用担心线程死锁等问题,但是如何在使用Widget时也使用异步操作呢?
Flutter提供了FutureBuilder来进行处理,FutureBuilder可以很容易的得到当前Widget的状态,并选择在加载数据时显示的内容.以及在可以使用时显示的内容.

FutureBuilder
FutureBuilder

首先给FutureBuilder设置future一个网络请求,,builder可以获取到当前的操作是那种状态,比如已完成.根据不同的状态来显示不同的内容.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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;
}
},
);
}
}

代码github