主要是學習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,包含基本的下拉刷新上拉加載的功能。網絡