Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
Fetching entries asynchronously
We want to fetch entries asynchronously from a remote server, but only when we scroll down to them. To do that, we will use the aforementionedListView.builder
constructor, along with FutureBuilder
.
Let’s assume that we have a function _fetchEntry
that looks like:
_fetchEntry(int index) async {
await Future.delayed(Duration(milliseconds: 500));
return {
'name': 'product $index',
'price': Random().nextInt(100)
};
}
- This function emulates a server that gives you the name and price of the product at the given index, and takes half a second to do that
Then we can call this function in our ListView.builder
:
ListView.builder(
itemBuilder: (context, index) {
return FutureBuilder(
future: this._fetchEntry(index),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return CircularProgressIndicator();
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
var productInfo = snapshot.data;
return ListTile(
leading: Icon(Icons.shopping_cart),
title: Text(productInfo['name']),
subtitle:
Text('price: ${productInfo['price']}USD'),
);
}
}
},
);
}
)
- The
FutureBuilder
is a widget that awaits a given future, and uses its builder function to build different widgets depending on the status of the future - When the future has not been called, or has been called but hasn’t returned its result yet. We are showing a
CircularProgressIndicator
. - When the future is done, we check to see if it returned with an error. If so, we show the text of the error
- Otherwise, we show a
ListTile
that displays the name and price returned from the future
And that’s it, when you start the app, you can see the entries getting loaded, then shown on screen, and as you scroll down, the same will happen for more and more entries