如下是四套列表和網格的常見需求async
FutrueBuilder
把 ListView
/GridView
和 _fetch
的 Future<T>
關聯起來。FutrueBuilder
相似CircularProgressIndicator
shrinkWrap: true
,或者使用 Sliver
/PagewiseSliver
版的控件@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _fetch(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child:CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.hasError) {
break;
} else {
var models = snapshot.data as List<YOURMODEL>;
return ListView(children: models.map((model) => YOURWIDGET(model: model)).toList());
}
break;
default:
break;
}
return Container();
});
}
Future<List<YOURMODEL>> _fetch() async {
Map map = await YOURHTTPClient.fetch();
List data = map["data"];
return Future.value(data.map((item) => YOURMODEL.fromJson(item)).toList());
}
複製代碼
static const _pageSize = 10;
@override
Widget build(BuildContext context) {
return PagewiseListView(
pageSize: _pageSize,
padding: EdgeInsets.all(0),
itemBuilder: (context, model, index) {
return YOURWIDGET(model: model);
},
pageFuture: (pageIndex) {
return _fetch(pageIndex: pageSize);
},
);
}
Future<List<YOURMODEL>> _fetch({int pageIndex}) async {
Map map = await YOURHTTPClient.fetch();
List data = map["data"];
return Future.value(data.map((item) => YOURMODEL.fromJson(item)).toList());
}
複製代碼
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _fetch(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.hasError) {
break;
} else {
var models = snapshot.data as List<YOURMODEL>;
return GridView.count(
childAspectRatio: 1,
crossAxisCount: 2,
children: models
.map((model) => YOURWIDGET(model: model))
.toList());
}
break;
default:
break;
}
return Container();
});
}
Future<List<YOURMODEL>> _fetch() async {
Map map = await YOURHTTPClient.fetch();
List data = map["data"];
return Future.value(data.map((item) => YOURMODEL.fromJson(item)).toList());
}
複製代碼
static const _pageSize = 10;
@override
Widget build(BuildContext context) {
return PagewiseGridView.count(
pageSize: _pageSize,
crossAxisCount: 2,
childAspectRatio: 1,
itemBuilder: (context, model, index) {
return YOURWIDGET(model: model);
},
pageFuture: (pageIndex) {
return _fetch(pageIndex: pageSize);
},
),
}
Future<List<YOURMODEL>> _fetch({int pageIndex}) async {
Map map = await YOURHTTPClient.fetch(pageIndex: pageIndex);
List data = map["data"];
return Future.value(data.map((item) => YOURMODEL.fromJson(item)).toList());
}
複製代碼