How to implement pull to refresh in Flutter?

How to implement pull to refresh in Flutter?

The pull-to-refresh (swipe-to-refresh) feature enables a user to pull down to fetch more data. So, in this article, we will see how to implement pull-to-refresh in Flutter. So, let’s get started.

How to implement pull-to-refresh in Flutter?

The pull-to-refresh is present in many modern apps. The pull-to-refresh feature can be implemented in those components that are scrollable. Let’s implement this feature in Flutter. If you are not familiar with flutter please visit flutter.dev before diving into this article. Flutter is all about widgets everything in flutter is nothing but widgets. Flutter also provides a widget to implement this feature as well as RefreshIndicator.

RefreshIndicator:

When the child’s scrollable descendant drifts too far, the animated circular progress indicator fades from view. If the indicator has been dragged long enough to become completely opaque, the onRefresh callback will be called when the scrolling is complete. The callback is expected to update the scrollable’s contents and then it returns the Future. The refresh indicator disappears after the callback’s has been completed.

To create a flutter application open terminal/ command and run the below command:

flutter create app_name
// app_name should be the name of your app

Example:
flutter create demo_app

After running this command you should have a folder with the specified app_name. Navigate into that folder and open lib/main.dart file.

Note: In order to implement the pull-to-refresh feature we are not going to use any other dependencies.

To create a RefreshIndicator use the below syntax:

RefreshIndicator(
  child: ...
  onRefresh: ...
)

These are required fields.

child: Should be a scrollable widget

onRefresh: A function that should return a future (Future is a type in dart).

We are going to implement this step by step.

Step 1:

As discussed above for RefreshIndicator to work we are going to need a scrollable component. So for that, we are going to use ListView. In this step, we are going to define some demo data for our app.

// Local State to display items in listview
List<String> _demoData;

// This method will run once widget is loaded
// i.e when widget is mounting
@override
void initState() {
  // initializing state / demo data
  _demoData = [
    "Flutter",
    "React Native",
    "Cordova/ PhoneGap",
    "Native Script"
  ];
  super.initState();
}

Step 2:

We are going to create our ListView with ListItem and AlwaysScrollingPhysics.

... some code

ListView.builder(
  itemBuilder: (ctx, idx) {
    // List Item
    return Card(
      child: ListTile(
        title: Text(_demoData[idx]),
      ),
    );
  },

  // Length of the list
  itemCount: _demoData.length,

  // To make listView scrollable
  // even if there is only a single item.
  physics: const AlwaysScrollableScrollPhysics(),
)

... some code

Step 3:

Finally wrapping ListView into RefreshIndicator to use the pull-to-refresh feature.

... some code

RefreshIndicator(
  child: ListView.builder(
    itemBuilder: (ctx, idx) {
      // List Item
      return Card(
        child: ListTile(
          title: Text(_demoData[idx]),
        ),
      );
    },

    // Length of the list
    itemCount: _demoData.length,

    // To make listView scrollable
    // even if there is only a single item.
    physics: const AlwaysScrollableScrollPhysics(),
  ),
  // Function that will be called when
  // user pulls the ListView downward
  onRefresh: () {
    return Future.delayed(
      Duration(seconds: 1),
      () {
        /// adding elements in list after [1 seconds] delay
        /// to mimic network call
        ///
        /// Remember: setState is necessary so that
        /// build method will run again otherwise
        /// list will not show all elements
        setState(() {
          _demoData.addAll(["Ionic", "Xamarin"]);
        });

        // showing snackbar
        _scaffoldKey.currentState.showSnackBar(
          SnackBar(
            content: const Text('Page Refreshed'),
          ),
        );
      },
    );
  },
)

... some code

In some cases, you will notice that the refresh indicator is not showing. To make it visible all the time please use physics. In Flutter all the scrollable widgets have physics properties.

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have been through how to implement pull to refresh in Flutter. Also, feel free to comment and provide your valuable suggestion.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields