How to use FutureBuilder inside SliverList
Use SliverFillRemaining
Widget build(BuildContext context) {
return new Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverFillRemaining(
child: FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.data == null)
return new Container(
child: Center(child: new CircularProgressIndicator()),
);
else
return Text(snapshot.data.name);
},
),
)
],
)
);
OR use SliverList
Widget build(BuildContext context) {
return new Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate([Container(
child: FutureBuilder(
future : getData(),
builder: (C,snap){
//do whatever you want
}
)
)]),
)
]
)
)
}
The children of a CustomScrollView
must be slivers, you can not use a FutureBuilder
.
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
],
);
},
);
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(...);
}
)
}
)