Chetan Khanna
Chetan Khanna

Reputation: 416

How can we paginate when before we reach max extent in flutter ListView?

I am currently paginating at max extent. I have written this code :

if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent) {
      setState(() {
        startIndex += 10;
      });
      context.read<MyBloc>().add(
            GetDataFromMyBloc(startIndex),
          );
    }

I have tried this test also :

 if (scrollController.position.pixels >
        scrollController.position.maxScrollExtent - 200) {}

But it's making scroll very laggy, because API is called multiple times. How can I make it call only one time ?

Upvotes: 4

Views: 2990

Answers (3)

Armstrong Loh&#227;ns
Armstrong Loh&#227;ns

Reputation: 61

In addition to indicating that you want to load the data when you reach the bottom of the page, it is important to add a second condition that prevents an unintentional scroll action from calling the loadData (or any other) method more than once, thus avoiding multiple calls and the data duplication if be a pagination!

Here an code example:

scrollController.addListener(() {
    if (scrollController.position.pixels > scrollController.position.maxScrollExtent - 200) {
        // you must use any way to verify if the state of page (or method) ISN'T in loading
        if (controller.state != loading) { 
            controller.loadData(controller.page);
        }
    }
});

Ignoring the condition | With condition != loading

On left, whithou the condition to verify if isn't loading data, on right, with the magic condition... 😁✨

Upvotes: 0

Sneha G Sneha
Sneha G Sneha

Reputation: 101

_scrollController.addListener(() {
  if (_scrollController.position.isScrollingNotifier.value ||
      _scrollController.position.extentAfter < 500) {
    if (_scrollController.position.atEdge) {
      if (_scrollController.position.pixels == 0) {
        // You're at the top.
      } else {
        // you are at the above bottom
        }
      }
    }
  }
});

This may be helpful for you

Upvotes: 0

reza
reza

Reputation: 1508

== is not a good practice in this case. try using something like:

if (scrollController.position.pixels >
        scrollController.position.maxScrollExtent - 200) {}

just you should handle in your stateful widget or your bloc not to fetch data multiple times.

Upvotes: 1

Related Questions