本文介绍了如何在SliverList中使用FutureBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将ListView
转换为CustomScrollView
,所以我需要将FutureBuilder
转换为SliverList
.
I want to covert ListView
to CustomScrollView
so I need to convert my FutureBuilder
into SliverList
.
这是我的代码:
class LatestNewsList extends StatefulWidget {
@override
_LatestNewsListState createState() => _LatestNewsListState();
}
class _LatestNewsListState extends State<LatestNewsList> {
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Data>>(
future: getQuake(),
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? NewsList(latestNews: snapshot.data,)
: Center(child: CircularProgressIndicator());
},
);
}
}
class NewsList extends StatelessWidget {
final List<Data> latestNews;
NewsList({this.latestNews});
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: latestNews.length,
itemBuilder: (context, index){
return new GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Browser(url: latestNews[index].post_link,)
)
);
},
child: new LatestNewsItem(
post_title: latestNews[index].post_title,
post_link: latestNews[index].post_link,
img_src: latestNews[index].img_src,
),
);
}
);
}
}
如何将相同的FutureBuilder逻辑转换为SliverList?
推荐答案
CustomScrollView
的子代必须是薄片,不能使用FutureBuilder
.
The children of a CustomScrollView
must be slivers, you can not use a FutureBuilder
.
相反,在将来完成时重建CustomScrollView
:
Instead, rebuild the CustomScrollView
when the future completes:
// build fixed items outside of the FutureBuilder for efficiency
final someOtherSliver = SliverToBoxAdapter(...);
return FutureBuilder<List<Data>>(
future: getQuake(), // this is a code smell. Make sure that the future is NOT recreated when build is called. Create the future in initState instead.
builder: (context, snapshot){
Widget newsListSliver;
if(snapshot.hasData) {
newsListSliver = SliverList(delegate: SliverChildBuilderDelegate(...))
} else {
newsListSliver = SliverToBoxAdapter(child: CircularProgressIndicator(),);
}
return CustomScrollView(
slivers: <Widget>[
someOtherSliver,
newsListSliver
],
);
},
);
如果您有多个依赖于Future
或Stream
的条,则可以链接构建器:
If you have multiple slivers which depend on Future
s or Stream
s, you can chain the builders:
return FutureBuilder<..>(
...
builder: (context, snapshot1) {
return FutureBuilder<..>(
...
builder: (context, snapshot2) {
return CustomScrollView(...);
}
)
}
)
这篇关于如何在SliverList中使用FutureBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!