DEV Community

Cover image for Getting to know Flutter: Pull to refresh with online data
TheOtherDev/s
TheOtherDev/s

Posted on

Getting to know Flutter: Pull to refresh with online data

Hi there! How you're doing? Everything's all right? Good. Today we 'll be doing a pretty easy task, a pull to refresh, while using a CMS in order to have online data and having more control on our example. Let's start!

What we'll need

Our ingredients will be:

  • A CMS account (we'll be using MBurger as it is free to start)
  • Android Studio
  • Flutter basic knowledge

I think it's a pretty easy recepie but it will also be very juicy!

MBurger configuration

First we'll need to create a free account on MBurger, go to this page to start. Then we can create a new project or use one provided template. We'll start from scratch.

Second we'll create a new block for our app. A block contains a list of sections which will be composed by:

  • Title -> Text
  • Content -> Text

We'll call it "Articles"

Alt Text

Next we'll create how our articles are composed. As we stated before we want to just add a title and a simple content, so we'll create 2 text elements.

Alt Text

As last thing we just need to create a section, so an article. We'll click on "Add Articles section" and create a simple Lorem Ipsum.

Alt Text

MBurger SDK

Before venturing into the depths of the MBurger SDK we'll need to create a API Key, which will be used to connect to our MBurger project in the app. Let's head to the settings and create an API Key. For our project we don't need anything more than read permissions, but we can also add write and delete permissions for our API Key.

Alt Text

Alt Text

We have done for now on MBurger website. Let's head to MBurger pub.dev!

Let's add MBurger dependency to a new Flutter project:

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.0
  mburger: ^2.0.7
Enter fullscreen mode Exit fullscreen mode

Then on initState method let's add our API Key:

@override
  void initState() {
    MBManager.shared.apiToken = 'MYAPIKEY';
    super.initState();
  }
Enter fullscreen mode Exit fullscreen mode

Then let's create an easy list and a Future for getting and parsing our data. We should need the block id of our articles block, which can be found directly in the MBurger dashboard.

@override
  void initState() {
    MBManager.shared.apiToken = 'MYAPIKEY';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
      ),
      backgroundColor: Colors.white,
      body: FutureBuilder<List<Article>>(
        future: getArticles(context),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                Article article = snapshot.data[index];
                return Column(
                  children: [
                    Text(article.title),
                    Text(article.content),
                  ],
                );
              },
            );
          }

          return Container();
        },
      ),
    );
  }

  Future<List<Article>> getArticles(BuildContext context) async {
    MBPaginatedResponse<MBSection> response =
        await MBManager.shared.getSections(
      blockId: MYBLOCK_ID,
      includeElements: true,
    );
    if (response.items != null) {
      List<Article> sections = response.items
          .map((section) => Article.fromSection(section))
          .toList();

      return sections;
    }
    return [];
  }
class Article {
  String title;
  String content;

  Article.fromSection(MBSection section) {
    var elements = section.elements;
    elements.forEach((key, element) {
      if (key == 'title' && element is MBTextElement) {
        title = element.value;
      } else if (key == 'content' && element is MBTextElement) {
        content = element.value;
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Pull to refresh implementation

We have all set, let's add our pull to refresh. Let's go to pub.dev and let's implement pull_to_refresh!

First we'll need to create a RefreshController, which will be attached to our Refresher:

  final RefreshController refreshControllerList =
      RefreshController(initialRefresh: false);
Enter fullscreen mode Exit fullscreen mode

Now wrap the ListView around a SmartRefresher, which is the main widget controlling the pull-to-refresh behavior. SmartRefresher has a lot of customization options, you can check more on the official page on pub.dev.

return SmartRefresher(
              controller: refreshControllerList,
              enablePullDown: true,
              onRefresh: () => _onRefresh(context),
              child: ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Article article = snapshot.data[index];
                  return Column(
                    children: [
                      Text(article.title),
                      Text(article.content),
                    ],
                  );
                },
              ),
            );
Enter fullscreen mode Exit fullscreen mode

The onRefresh parameter should point to an async function which should call again our future:

void _onRefresh(BuildContext context) async {
    try {
      await getArticles(context);
      refreshControllerList.refreshCompleted();
      setState(() {});
    } catch (error) {
      refreshControllerList.refreshFailed();
      print(error);
    }
  }
Enter fullscreen mode Exit fullscreen mode

While the app is open then we'll need to add a new section to our MBurger project. Then with a swipe the list will be refreshed and we'll see the new item on our list. All done!!

Want to check more awesome tutorials? Click here!

Top comments (1)

Collapse
 
chris2phern profile image
chris2phern

This is not working started new flutter project and the code for pull refresh is not working. I really like your code though just want it to work would use in IOS and Android. I am new here the last 3 codes you have where do they go can you send me the whole code as it would work from top to bottom?

Thank You

where does this final RefreshController refreshControllerList =
RefreshController(initialRefresh: false);

Where does this go?return SmartRefresher(
controller: refreshControllerList,
enablePullDown: true,
onRefresh: () => _onRefresh(context),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
Article article = snapshot.data[index];
return Column(
children: [
Text(article.title),
Text(article.content),
],
);
},
),
);