Ad

How To Trigger Function On End Of Carousel Slider In Flutter?

- 1 answer

I have used the carousel_slider package for displaying posts to my users in my application. I want to load more posts whenever the user reaches the last post in the carousel. Where can I trigger the function that will add more data to the list of items, which in case is

homeData

This is how my code looks:

@override
Widget build(BuildContext context) {
  return RefreshIndicator(
    onRefresh: getMoreData, //fetches new post on refresh
    child: CarouselSlider(
      options: CarouselOptions(
        height: 650,
        enableInfiniteScroll: false,
        aspectRatio: 2.0,
        enlargeCenterPage: true,
        scrollDirection: Axis.vertical,
      ),
      items: homeData, //list of widgets that are displayed in the carousel
    ),
  );
}
Ad

Answer

You can give a callback to onPageChanged, which will be called whenever the post is swiped.

Here's how you can do it :

List itemList = [1,2,3,4,5];


CarouselSlider(
      options: CarouselOptions( 
        height: 400.0,
        onPageChanged: (index, reason) {
          if(index == itemList.length - 1) {
            //do whatever you want to do on your last page change
          }
        },
      ),
      items: itemList.map((i) {
        return Builder(
          builder: (BuildContext context) {
            return Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.symmetric(horizontal: 5.0),
              decoration: BoxDecoration(
                color: Colors.amber
              ),
              child: Text('text $i', style: TextStyle(fontSize: 16.0),)
            );
          },
        );
      }).toList(),
    )
Ad
source: stackoverflow.com
Ad