CodeChai
Published in

CodeChai

Adding Swipe To Refresh to Flutter app

In Android app you can implement swipe to refresh by wrapping your ListView(or GridView) inside SwipeRefreshLayout, while in iOS UIRefreshControl is used for same.

For Flutter there is RefreshIndicator

A widget that supports the Material “swipe to refresh” idiom.

When child of RefreshIndicator is over scrolled , an animated circular progress indicator is displayed & onRefresh callback is called. Callback returns a future, after complete of which UI is updated & refresh indicator disappears.

In this example we will load random user profile using free API RandomUser, which provides random user on each refresh.

First things first , lets create a StatefulWidget & State for that widget.

Now lets create User model & network call to fetch user

More on network call on flutter https://medium.com/@sharmadhiraj.np/network-call-with-progress-error-retry-in-flutter-8b58585f0b26

Now lets create default user data & implement build method(of State).

At this moment if we start SwipeToRefreshExample widget output will be default user with placeholder image.

Things to remember while implementing RefreshIndicator is

  • RefreshIndicator requires key to implement state.
  • onRefresh(RefreshCallback) method required completable future.
  • child is typically ListView or CustomScrollView.

Add RefreshIndicatorState inside our state class

Update body of build inside state : Wrap code we wrote above inside build to ListView & then RefreshIndicator.

_refresh() method : this method call getUser() which returns User on future. When user is returned by getUser(), our user(of state) is updated & setState is called for rebuild.

Done our SwipeToRefresh is ready.

One thing missing here is user needs to swipe to see data at start, we can make data load automatically at start by updating indicator state inside initState once widget is build.

Now if you want to add a refresh button on toolbar which acts same as swipe. Update AppBar, add actions as

Full code for this example is available here

Thanks ! Question & Feedback Welcome !!

The Flutter Pub is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts etc. about this great technology to teach you how to build beautiful apps with it. You can find us on Facebook, Twitter, and Medium or learn more about us here. We’d love to connect! And if you are a writer interested in writing for us, then you can do so through these guidelines.

--

--

A place for programmers and writers turning coffee/tea into code, one line at a time.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store