Flutter Pull to refresh

Hi Guys, Welcome to proto coders point, In this Flutter Tutorial, we gonna Implement the pull to refresh the flutter package library.

Demo on how the final code will work for pull to refresh

flutter pull down to refresh package library

Brief about the pull to refresh

This widget is very useful when the user wants to scroll down to refresh the contents and even this widget can be pull up to load new content to the user. This widget Support both Android and iOS devices.

let’s begin the Implementation of pull to refresh flutter package library.

Step 1: Add Pull to Refresh Dependencies

Open pubspec.yaml file from your flutter project then you need to add the library dependencies.

dependencies:
  pull_to_refresh: ^1.5.8 // add this line

Here version may get updated so kindly check for the latest version on the official Flutter library

Once you add the dependencies you need to click on Packages Get then all the class will be added to your flutter project.

adding pull_to_refresh dependencies

Step 2: Import the flutter pull to refresh class where required

Then now once you have added the dependencies now you need to just import the library class there every required, In my case, I have imported in main. dart file

import 'package:pull_to_refresh/pull_to_refresh.dart';

Step 3:  Brief Snippet detail about SmartRefresh Flutter Widget

SmartRefresher(
      {Key key,
      @required this.controller,
      this.child,
      this.header,
      this.footer,
      this.enablePullDown: true,
      this.enablePullUp: false,
      this.enableTwoLevel: false,
      this.onRefresh,
      this.onLoading,
      this.onTwoLevel,
      this.onOffsetChange,
      this.dragStartBehavior,
      this.primary,
      this.cacheExtent,
      this.semanticChildCount,
      this.reverse,
      this.physics,
      this.scrollDirection,
      this.scrollController})

Here we need a controller that controls the loading and refreshing data when a user pulls down to refresh,

This SmartRefresh can have many properties example :

header: WaterDropMaterailHeader() used to show a header with a water drop Header animation effect.

enablePullDown true: to activity the pull-down to refresh

enablePullUp true: to activity the pull up to refresh

onRefresh: What should be performed when the user pulls down / pull up.

onLoading: basically used when we want to show a progress indicator to the user.

Step 4: Basic Snippet codes

List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()

    if (mounted)
      setState(() {
        items.add((items.length + 1).toString());
      });
    _refreshController.loadComplete();
  }

Step 5: Complete code

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
    "Item 7",
    "Item 8"
  ];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()

    print(items);
    if (mounted)
      setState(() {
        items.add((items.length + 1).toString());
      });
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Data time field"),
      ),
      body: Scrollbar(
        child: SmartRefresher(
          enablePullDown: true,
          header: WaterDropMaterialHeader(),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus status) {
              Widget body;
              if (status == LoadStatus.idle) {
                body = Text("pull up load");
              } else if (status == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (status == LoadStatus.failed) {
                body = Text("Load Failed!Click retry!");
              } else if (status == LoadStatus.canLoading) {
                body = Text("release to load more");
              } else {
                body = Text("No more Data");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            itemBuilder: (c, i) => Card(child: Center(child: Text(items[i]))),
            itemExtent: 100.0,
            itemCount: items.length,
          ),
        ),
      ),
    );
  }
}