主要是学习FutureBuilder的使用,利用FutureBuilder来实现懒加载,并能够监听加载过程的状态 这个Demo是加载玩Android的一个页面的列表数据html
常常有这些场景,就是先请求网络数据并显示加载菊花,拿到数据后根据请求结果显示不一样的界面, 好比请求出错就显示error界面,响应结果里面的列表数据为空的话,就显示数据为空的界面,有数据的话, 就把列表数据加载到列表中进行显示.android
const FutureBuilder({
Key key,
this.future,//获取数据的方法
this.initialData,
@required this.builder//根据快照的状态,返回不一样的widget
}) : assert(builder != null),
super(key: key);
复制代码
future就是一个定义的异步操做,注意要带上泛型,否则后面拿去snapshot.data的时候结果是dynamic的 snapshot就是future这个异步操做的状态快照,根据它的connectionState去加载不一样的widget 有四种快照的状态:git
enum ConnectionState {
//future还未执行的快照状态
none,
//链接到一个异步操做,而且等待交互,通常在这种状态的时候,咱们能够加载个菊花
waiting,
//链接到一个活跃的操做,好比stream流,会不断地返回值,并尚未结束,通常也是能够加载个菊花
active,
//异步操做执行结束,通常在这里能够去拿取异步操做执行的结果,并显示相应的布局
done,
}
复制代码
下面的官方的例子。github
FutureBuilder<String>(
future: _calculation, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return Text('Result: ${snapshot.data}');
}
return null; // unreachable
},
)
复制代码
网络请求:利用Dio库来请求玩Android的知识体系列表,api:www.wanandroid.com/tree/jsonjson
序列化json:利用json_serializable来解析返回的json数据api
布局:加载过程显示CircularProgressIndicator,加载完成把数据显示到ListView中, 加载为空或者加载出错的话,显示相应的提示页面,并能够进行重试请求 通常。咱们的列表页面都是有下拉刷新的功能,因此这里就用RefreshIndicator来实现。bash
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'entity.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: FutureBuilderPage(),
);
}
}
class FutureBuilderPage extends StatefulWidget {
@override
_FutureBuilderPageState createState() => _FutureBuilderPageState();
}
class _FutureBuilderPageState extends State<FutureBuilderPage> {
Future future;
@override
void initState() {
// TODO: implement initState
super.initState();
future = getdata();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("知识体系"),
actions: <Widget>[
new IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: null)
],
),
body: buildFutureBuilder(),
floatingActionButton: new FloatingActionButton(onPressed: () {
setState(() {
//测试futurebuilder是否进行不必的重绘操做
});
}),
);
}
FutureBuilder<List<Data>> buildFutureBuilder() {
return new FutureBuilder<List<Data>>(
builder: (context, AsyncSnapshot<List<Data>> async) {
//在这里根据快照的状态,返回相应的widget
if (async.connectionState == ConnectionState.active ||
async.connectionState == ConnectionState.waiting) {
return new Center(
child: new CircularProgressIndicator(),
);
}
if (async.connectionState == ConnectionState.done) {
debugPrint("done");
if (async.hasError) {
return new Center(
child: new Text("ERROR"),
);
} else if (async.hasData) {
List<Data> list = async.data;
return new RefreshIndicator(
child: buildListView(context, list),
onRefresh: refresh);
}
}
},
future: future,
);
}
buildListView(BuildContext context, List<Data> list) {
return new ListView.builder(
itemBuilder: (context, index) {
Data bean = list[index];
StringBuffer str = new StringBuffer();
for (Children children in bean.children) {
str.write(children.name + " ");
}
return new ListTile(
title: new Text(bean.name),
subtitle: new Text(str.toString()),
trailing: new IconButton(
icon: new Icon(
Icons.navigate_next,
color: Colors.grey,
),
onPressed: () {}),
);
},
itemCount: list.length,
);
}
//获取数据的逻辑,利用dio库进行网络请求,拿到数据后利用json_serializable解析json数据
//并将列表的数据包装在一个future中
Future<List<Data>> getdata() async {
debugPrint("getdata");
var dio = new Dio();
Response response = await dio.get("http://www.wanandroid.com/tree/json");
Map<String, dynamic> map = response.data;
Entity entity = Entity.fromJson(map);
return entity.data;
}
//刷新数据,从新设置future就好了
Future refresh() async {
setState(() {
future = getdata();
});
}
}
复制代码
由于这个场景会常常被用到,若是要一直这样写的话,代码量仍是挺多的,并且还挺麻烦的。 因此下一步是封装一个通用的listview,包含基本的下拉刷新上拉加载的功能。网络