Here we go again with some more amazing stuff on Flutter. Previously we looked into the way how you can fetch data from an API over a network. You can read it here.
Let’s talk a bit more practical now. When you fetch data from a remote data source, chances are that it gets updated anytime after you fetch your copy. So there must be some way to get the updated data. Thankfully, Flutter understands this need and provides a built-in widget for it called RefreshIndicator.
Here’s a must-read from the official documentation:
When the child’s Scrollable descendant overscrolls, an animated circular progress indicator is faded into view. When the scroll ends, if the indicator has been dragged far enough for it to become completely opaque, the onRefresh callback is called. The callback is expected to update the scrollable’s contents and then complete the Future it returns.
Let’s see that in practice. We are going to use the same idea that we used in the earlier blog but this time, with RefreshIndicator.
Here’s the simple but complete App code:
Let’s understand the code below:
- The UserList is a StatefulWidget because we are updating the list by pulling the data again from the API.
- In the fetchUser() method, we are fetching random users using the same random user API that we used earlier.
- In the same method, we assigned the result of the API i.e list of users under the setState method. This will call the build method again to show the list on the screen.
- We wrapped the ListView.builder in RefreshIndicator to implement the pull to refresh mechanism.
- RefreshIndicator takes two main arguments — the child and the onRefresh handle. The child should be a scrollable widget such as ListView or CustomScrollView. the onRefresh takes a method which is called when the user pulls the list down enough to trigger this event. It should be a Future that handles the data update logic.
If you take a look into the code in this article and compare it with the previous one, you’ll find that the only difference is that we wrapped our list inside RefreshIndicator and nothing else.
We can even use a better approach by using Firebase’s Cloud Firestore to eliminate the need to refresh data. Let’s stay tuned for this upcoming article :)