Getting to know Flutter: Pull to refresh with online data

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

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.

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.

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.

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

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

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

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;
      }
    });
  }
}

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);

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),
                    ],
                  );
                },
              ),
            );

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);
    }
  }

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!!

Add a Comment

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