A flutter carousel widget, support infinite scroll, and custom child widget.

Last update: Aug 16, 2022

carousel_slider

A carousel slider widget.

Features

  • Infinite scroll
  • Custom child widgets
  • Auto play

Supported platforms

  • Flutter Android
  • Flutter iOS
  • Flutter web
  • Flutter desktop

Live preview

https://serenader2014.github.io/flutter_carousel_slider/#/

Note: this page is built with flutter-web. For a better user experience, please use a mobile device to open this link.

Installation

Add carousel_slider: ^3.0.0 to your pubspec.yaml dependencies. And import it:

import 'package:carousel_slider/carousel_slider.dart';

How to use

Simply create a CarouselSlider widget, and pass the required params:

CarouselSlider(
  options: CarouselOptions(height: 400.0),
  items: [1,2,3,4,5].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(),
)

Params

CarouselSlider(
   items: items,
   options: CarouselOptions(
      height: 400,
      aspectRatio: 16/9,
      viewportFraction: 0.8,
      initialPage: 0,
      enableInfiniteScroll: true,
      reverse: false,
      autoPlay: true,
      autoPlayInterval: Duration(seconds: 3),
      autoPlayAnimationDuration: Duration(milliseconds: 800),
      autoPlayCurve: Curves.fastOutSlowIn,
      enlargeCenterPage: true,
      onPageChanged: callbackFunction,
      scrollDirection: Axis.horizontal,
   )
 )

Since v2.0.0, you'll need to pass the options to CarouselOptions. For each option's usage you can refer to carousel_options.dart.

If you pass the height parameter, the aspectRatio parameter will be ignored.

Build item widgets on demand

This method will save memory by building items once it becomes necessary. This way they won't be built if they're not currently meant to be visible on screen. It can be used to build different child item widgets related to content or by item index.

CarouselSlider.builder(
  itemCount: 15,
  itemBuilder: (BuildContext context, int itemIndex) =>
    Container(
      child: Text(itemIndex.toString()),
    ),
)

Carousel controller

In order to manually control the pageview's position, you can create your own CarouselController, and pass it to CarouselSlider. Then you can use the CarouselController instance to manipulate the position.

class CarouselDemo extends StatelessWidget {
  CarouselController buttonCarouselController = CarouselController();

 @override
  Widget build(BuildContext context) => Column(
    children: <Widget>[
      CarouselSlider(
        items: child,
        carouselController: buttonCarouselController,
        options: CarouselOptions(
          autoPlay: false,
          enlargeCenterPage: true,
          viewportFraction: 0.9,
          aspectRatio: 2.0,
          initialPage: 2,
        ),
      ),
      RaisedButton(
        onPressed: () => buttonCarouselController.nextPage(
            duration: Duration(milliseconds: 300), curve: Curves.linear),
        child: Text('→'),
      )
    ]
  );
}

CarouselController methods

.nextPage({Duration duration, Curve curve})

Animate to the next page

.previousPage({Duration duration, Curve curve})

Animate to the previous page

.jumpToPage(int page)

Jump to the given page.

.animateToPage(int page, {Duration duration, Curve curve})

Animate to the given page.

Screenshot

Basic text carousel demo:

simple

Basic image carousel demo:

image

A more complicated image carousel slider demo:

complicated image

Fullscreen image carousel slider demo:

fullscreen

Image carousel slider with custom indicator demo:

indicator

Custom CarouselController and manually control the pageview position demo:

manual

Vertical carousel slider demo:

vertical

Simple on-demand image carousel slider, with image auto prefetch demo:

prefetch

No infinite scroll demo:

noloop

All screenshots above can be found at the example project.

License

MIT

GitHub

https://github.com/serenader2014/flutter_carousel_slider
Comments
  • 1. Possible to load x images in advance to cache?

    When building item widgets on demand, is it possible to load x number of widgets in advance? ie, with an image slider, have the next two images loading into cache while still offscreen.

    Reviewed by guit4eva at 2020-03-16 14:07
  • 2. Flutter web support?

    Anytime soon?

    Until then, here is my fork with dependencies fixed. I also removed the examples since they don't work anyway.

    https://github.com/CiriousJoker/flutter_carousel_slider

    Reviewed by ciriousjoker at 2019-08-21 14:19
  • 3. Remove Center from each child

    The plugin is forcing a center widget in each of its elements, constraining the application of this plugin.

    E.g If i want the carousel to have the image at top of the screen it would be almost impossible because of this Center widget without using some obscure hacky stuff ;)

    There is some way to don't force this behavior in the carousel?

    Reviewed by qaniel at 2020-01-22 17:54
  • 4. Add feature to pause auto play when user input is detected

    Added a variable pauseOnUserImput which takes a Duration. If autoPlay is set to true and pauseOnUserInput is not null, the PageView will be wrapped in a GestureDetector listening for pan gestures.

    Also did some minor consistency changes, i.e. Hard typed a few untyped values and removed the 'new' keywords. Almost all values were already hard typed and 'new' was used in only a few places. Now each line of code follows the same code convention.

    My linting options were different from the projects, so I did my best to follow the repo manually. Feel free to auto format the code with the previously used setting!

    Premise: When using a sliding carousel you might want the user to be able to interact with a slide. For now, the user can swipe back if he/she see something they like, but the carousel will keep iterating through its children. This forces the user to constantly swipe back to the page they were interacting with. For example, imagen a commercial display rolling adds in a waiting room. If something interest a person he or she might want to pause the slide to read all the information.

    This feature lets the developer implement a way too pause the auto play feature for a set amount of time, resetting each time new input is detected. This way the user can interact with the application and after they leave, it will go back to circling the widgets.

    Reviewed by joelbrostrom at 2019-02-14 13:41
  • 5. How to pause auto play?

    Hi

    How can we pause autoplay so that while carousel is out of screen or to say out of visibility it will automatically pause or any method to pause it....?

    Reviewed by LoveAndroDev at 2020-05-06 09:22
  • 6. Add toggle item loop feature

    By popular demand I created a simple bool, loopItems, when set to false will reduce the item count to items.count.

    This results in a static length page viewer that still retains all the other benefits of this library (animations, buttons, autoplay etc...).

    I also added comments to this and the vertical scroll feature i rebased against. I realized now that it still have a PR open, but I added some info about it in the Readme and change-log.

    I suggest we add the features together and bump the version code to 1.2.0 (major.minor.patch) insteadof 1.2.0 and then 1.3.0 imminently after.

    Reviewed by joelbrostrom at 2019-03-04 13:24
  • 7. onPageChanged with manual reason is called randomly while using carouselController

    The issue isn't easy to reproduce. I'm changing the page using carouselController. Also allowing user to change page manually. Sometimes when I change the carousel to an item. _carouselPageChanged called to a random index (I guess an item between current item and next item) with reason manual.

    below is my _carouselPageChanged

      _carouselPageChanged(int index, CarouselPageChangedReason reason) {
        if (reason != CarouselPageChangedReason.manual) return;
        final id = _ids[index];
        if (id != null) {
          // TODO FIX sometime called while carousel is animating to other item
          _handleItemChange(id);
        } else {
          // TODO handle unexpected error
        }
      }
    
    
    Reviewed by MartinJLee at 2020-06-19 12:01
  • 8. fix empty blink when controller.page is null on first render

    As reported on issue #41, it is possible to see an empty blink when the first page is rendered.

    Instead of creating an empty Container before the re-render call from delayed future, we can use a NotificationListener and change the page position value based on the user interaction to re-render the widget with the correct value.

    No hack needed :)

    Reviewed by haroldolivieri at 2019-04-15 09:37
  • 9. Non-looping setting

    Is there a way to prevent the carousel from looping around to the start?

    In other words - if I have 3 items, I want to prevent the user from sliding past the third item. They would need to swipe the other direction to get back to the first item.

    I love the plugin but I want to use it for a set of cards that someone can swipe through and it would make more sense to have the user swipe back and forth if there are only 2 cards.

    Reviewed by brettpappas at 2018-07-25 18:51
  • 10. Different layout after v2 update

    Good morning, after I've update the library to the new v2.0.1 version I noticed a different layout in the carousel using the same code. It seems that the gap/blank space between image has been increased. v1.4.1:

    CarouselSlider.builder(
                      autoPlay: true,
                      pauseAutoPlayOnTouch: const Duration(seconds: 10),
                      enlargeCenterPage: true,
                      aspectRatio: 2.0,
                      itemCount: _tourImages.length,
                      itemBuilder: (BuildContext context, int itemIndex) =>
                          ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        child: CachedNetworkImage(
                          imgUrl: _tourImages[itemIndex],
                          canShowFullScrenn: true,
                        ),
                      ),
                    ),
    

    image

    v2.0.1:

    CarouselSlider.builder(
                      options: CarouselOptions(
                        autoPlay: true,
                        enlargeCenterPage: true,
                        aspectRatio: 2.0,
                      ),
                      itemCount: _tourImages.length,
                      itemBuilder: (BuildContext context, int itemIndex) =>
                          ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        child: CachedNetworkImage(
                          imgUrl: _tourImages[itemIndex],
                          canShowFullScrenn: true,
                        ),
                      ),
                    ),
    

    image

    Is it possible to reduce it? Is it an expected behaviour?

    Reviewed by enricobenedos at 2020-05-06 21:37
  • 11. Carousel options do not respond to state change

    I have a boolean variable that updates when the device switches between landscape and portrait mode, then I use ternary operators for different values for the carousel options to get a more responsive UI.

    However, the carousel does not seem to respond to the changes in the variable that tracks device orientation. calling setState((){}) does not work. The only way I can get the carousel to reflect the change in state is to completely rebuild the widget.

    This is the code for something similar to what I'm trying to achieve. In the code below I use the FAB to swap out and back in the carousel before it reflects the desired changes.

    I have also screen recorded the undesired behaviour here

    import 'package:carousel_slider/carousel_slider.dart';
    import 'package:flutter/material.dart';
    
    class TestPage extends StatefulWidget {
      static const String id = '/TestPage';
    
      @override
      _TestPageState createState() => _TestPageState();
    }
    
    class _TestPageState extends State<TestPage> {
      bool showCarousel;
    
      @override
      void initState() {
        showCarousel = true;
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        bool isLandscape =
            MediaQuery.of(context).orientation == Orientation.landscape;
    
        return Scaffold(
          appBar: AppBar(
            title: Text('Carousel Slider'),
            centerTitle: true,
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          floatingActionButton: FloatingActionButton.extended(
            onPressed: () {
              setState(() {
                showCarousel = !showCarousel;
              });
            },
            label: Text('Swap'),
            icon: Icon(Icons.refresh),
          ),
          body: Container(
            child: Center(
              child: showCarousel
                  ? CarouselSlider.builder(
                      itemCount: 9,
                      itemBuilder: (context, i) {
                        return Container(
                          width: 300.0,
                          height: 400.0,
                          padding: EdgeInsets.all(16.0),
                          color: Colors.primaries.reversed.toList()[i],
                        );
                      },
                      options: CarouselOptions(
                        height: 500.0,
                        autoPlay: true,
                        autoPlayCurve: Curves.easeOut,
                        viewportFraction: isLandscape ? 0.3 : 1.0,
                        enlargeCenterPage: isLandscape,
                      ),
                    )
                  : Text('Swapping...'),
            ),
          ),
        );
      }
    }
    
    
    Reviewed by thearthurdev at 2020-05-06 00:26
  • 12. padEnds:false along with autoplay won't work correctly

    Hello, Thank you for this great library, it is very convenient to use.

    To the issue itself: Disabling padEnds, along with enabling the autoplay feature, causes weird behavior while autoplay scrolling. Seems as the scrollbar isn't aware that the slider no longer has padding in the ends, and tries to scroll over it.

    Reviewed by idish at 2022-07-27 08:05
  • 13. Scroll through multiple items

    Hi! Is it possible to scroll through multiple items in one scroll? It seems like right now we can only swipe through one item at a time. Would appreciate any help/advice :)

    Reviewed by greg-woo at 2022-07-26 07:20
  • 14. Possibility of including videos in addition to images?

    With flutter_carousel_slider we can include dynamic GIFs in addition to plain image files.

    This is great, and it would be even more awesome to also have the possibility of including videos.

    Any thoughts?

    Thanks.

    Reviewed by farr64 at 2022-07-06 16:22
  • 15. autoplayDelay Can it be dynamic?

    autoplayDelay Can it be dynamic? There are 5 images. The first one shows 3 seconds, the second chapter shows 5 seconds, and the third one shows 10 seconds. AutoplayDelay is dynamic. Currently, it looks like you can only set it once

    Reviewed by yj229201093 at 2022-07-01 09:03

Related

A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network, zoom pan image, photo view, slide out page, editor(crop,rotate,flip), paint custom etc.
A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network, zoom pan image, photo view, slide out page, editor(crop,rotate,flip), paint custom etc.

extended_image Language: English| 中文简体 A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network

Aug 16, 2022
A Flutter image editor with support for paint, text, filters, emojis, stickers and more
A Flutter image editor with support for paint, text, filters, emojis, stickers and more

Flutter Image Editor Plugin with simple, easy support for image editing using Paints, Text, Filters, Emoji and Sticker like stories.

Aug 11, 2022
Generate & add your custom icons
Generate & add your custom icons

The custom icons will be converted into a ttf font file, which will be added into the project. An automatically generated Dart file will be added, allowing icons to be used like Icon(CustomIcons.email)

Apr 6, 2022
📸 Easy to use yet very customizable zoomable image widget for Flutter, Photo View provides a gesture sensitive zoomable widget. Photo View is largely used to show interacive images and other stuff such as SVG.
📸 Easy to use yet very customizable zoomable image widget for Flutter, Photo View provides a gesture sensitive zoomable widget. Photo View is largely used to show interacive images and other stuff such as SVG.

Flutter Photo View A simple zoomable image/content widget for Flutter. PhotoView enables images to become able to zoom and pan with user gestures such

Aug 8, 2022
Crop any widget/image in Android, iOS, Web and Desktop with fancy and customizable UI, in pure Dart code.
Crop any widget/image in Android, iOS, Web and Desktop with fancy and customizable UI, in pure Dart code.

crop A Flutter package for cropping any widget, not only images. This package is entirely written in Dart and supports Android, iOS, Web and Desktop.

Jul 21, 2022
A Flutter widget that paints an image and moves it at a slower speed than the main scrolling content.
A Flutter widget that paints an image and moves it at a slower speed than the main scrolling content.

A Flutter widget that paints an image and moves it at a slower speed than the main scrolling content. Installation Add dependency to your pubspec.yaml

May 26, 2022
SVG parsing, rendering, and widget library for Flutter
SVG parsing, rendering, and widget library for Flutter

flutter_svg Draw SVG (and some Android VectorDrawable (XML)) files on a Flutter Widget. Getting Started This is a Dart-native rendering library. Issue

Aug 15, 2022
A flutter plugin which provides Crop Widget for cropping images.
A flutter plugin which provides Crop Widget for cropping images.

A flutter plugin which provides Crop Widget for cropping images. crop_your_image provides only minimum UI for deciding cropping area inside images. Other UI parts, such as "Crop" button or "Change Aspect Ratio" button, need to be prepared by each app developers.

Aug 9, 2022
A flutter package to convert any widget to an Image.
A flutter package to convert any widget to an Image.

Davinci A package to convert any widget to an image which can be saved locally or can be shared to other apps and chats. ?? Preview ℹ️ Usage Prerequis

May 15, 2022
Build a fancy looking avatar widget with a colorfull ring around the image
Build a fancy looking avatar widget with a colorfull ring around the image

Build a fancy looking avatar widget with a colorfull ring around the image

Feb 19, 2022
Simple and effective cross platform image saver for flutter, supported web and desktop

Simple and effective cross platform image saver for flutter, supported web and desktop

Mar 28, 2022
Loading indicator GIFs. Material and Cupertino (Android and iOS) loading indicators in assorted sizes. Use as placeholders for loading remote image assets. Demo: https://gallery.codelessly.com/flutterwebsites/loadinggifs/
Loading indicator GIFs. Material and Cupertino (Android and iOS) loading indicators in assorted sizes. Use as placeholders for loading remote image assets. Demo: https://gallery.codelessly.com/flutterwebsites/loadinggifs/

Loading GIFs High quality Android and iOS loading spinners. View Demo Loading GIFs is a collection of high fidelity loading animations in GIF format.

Jun 13, 2022
A Flutter plugin for Android and iOS supports cropping images
A Flutter plugin for Android and iOS supports cropping images

Image Cropper A Flutter plugin for Android and iOS supports cropping images. This plugin is based on two different native libraries so it comes with d

Aug 17, 2022
Download, cache and show images in a flutter app

Cached network image A flutter library to show images from the internet and keep them in the cache directory. How to use The CachedNetworkImage can be

Aug 9, 2022
Flutter plugin that allows you to display multi image picker on iOS and Android. 👌🔝🎉
Flutter plugin that allows you to display multi image picker on iOS and Android. 👌🔝🎉

IMPORTANT: This repository has been archived and no longer mantained. As I don't have time anymore to work on the package it became very outdated. For

Apr 29, 2021
Use lottie in flutter for both iOS and Android

flutter_lottie Use Lottie in Flutter. Supports both iOS and Android using lottie-ios and lottie-android Current Status Supports most features that bot

Aug 11, 2022
A simple and easy flutter demo to crop image

flutter_image_crop A simple demo to crop image on flutter easily. A Chinese version of this document can be found here Flutter_image_crop Plugin will

Jul 8, 2021
Multiavatar is a free and open-source multicultural avatar maker.
Multiavatar is a free and open-source multicultural avatar maker.

Flutter Wrapper for Multiavatar Multiavatar is a multicultural avatar maker. Multiavatar represents people from multiple races, multiple cultures, multiple age groups, multiple worldviews and walks of life.

Jul 22, 2022
Minimal Unsplash Android App to easily search and download images
Minimal Unsplash Android App to easily search and download images

Minimal Unsplash Android App to easily search and download images

Aug 3, 2022