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

Overview

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

Comments
  • Possible to load x images in advance to cache?

    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.

    opened by guit4eva 19
  • Flutter web support?

    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

    opened by ciriousjoker 18
  • Remove Center from each child

    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?

    opened by qaniel 15
  • Add feature to pause auto play when user input is detected

    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.

    opened by joelbrostrom 14
  • How to pause auto play?

    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....?

    opened by LoveAndroDev 13
  • Add toggle item loop feature

    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.

    opened by joelbrostrom 12
  • onPageChanged with manual reason is called randomly while using carouselController

    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
        }
      }
    
    
    opened by MartinJLee 11
  • fix empty blink when controller.page is null on first render

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

    opened by haroldolivieri 11
  • Non-looping setting

    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.

    feature 
    opened by brettpappas 11
  • Different layout after v2 update

    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?

    opened by enricobenedos 10
  • Carousel options do not respond to state change

    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...'),
            ),
          ),
        );
      }
    }
    
    
    opened by thearthurdev 10
  • How to change  the

    How to change the "autoPlayInterval" dynamically ?

    Hello ! I want change the "autoPlayInterval" value when carousel is playing,but I can't find a way to update it. It will not be updated when use "setState(()=>{ _autoPlayInterval = n })" So how can I update it ? Thank you!

    opened by devchenli 0
  • error if enableInfiniteScroll: false,

    error if enableInfiniteScroll: false,

    if i put enableInfiniteScroll: false, i get this error when i reach last image or first image

    ======== Exception caught by gesture =============================================================== The following assertion was thrown while handling a gesture: 'package:flutter/src/widgets/overscroll_indicator.dart': Failed assertion: line 243 pos 14: 'notification.metrics.axis == widget.axis': is not true.

    Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause. In either case, please report this assertion by filing a bug on GitHub: https://github.com/flutter/flutter/issues/new?template=2_bug.md

    opened by laith261 0
  • Multiple items with end-padding

    Multiple items with end-padding

    When displaying multiple items on the screen (with enableInfiniteScroll: false and pageSnapping: true), the first and last item in the carousel must reach the center of the screen before scroll stops working. Or, according to the documentation of padEnds: If this is set to true and viewportFraction < 1.0, padding will be added such that the first and last child slivers will be in the center of the viewport when scrolled all the way to the start or end, respectively..

    This gives the following result:

    example1

    Settings padEnds: false gives the following result:

    example2

    Instead, I would like to have a gutter on either side of the carousel. Goal:

    example3

    Is there a way to achieve this result? So far, I have attempted:

    1. Add a padding / margin to the first and last item in the list. Unfortunately, all items are uniformly sized so they do not maintain their aspect ratio (the first and last are now less wide than the other items).
    2. Add a container with padding around the CarouselSlider with clipBehaviour: Clip.none. This provides the intended result visually, but now the partially cut-off next item (achieved with viewportFraction < 1) is removed after scrolling when it is located in this padding because it is no longer part of the CarouselSlider viewport.
    3. Add a row with multiple items per 'page', so that the page centers in the screen and not the individual items. The problem with this setup is that the last page may not contain the correct amount of items, which gives a similar result with a lot of white space.

    Thanks!

    opened by rvanderlinden 0
  • fix: clear timer if widget was unmounted

    fix: clear timer if widget was unmounted

    In more complex application with multiple tabs and custom autoplay running around, there might be a scenario, that page gets disposed (tab is switched), yet timer it still being run. Once timer hits - widget is not mounted (l133) thus throwing

    [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
    Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
    #0      State.context.<anonymous closure> (package:flutter/src/widgets/framework.dart:935:9)
    #1      State.context (package:flutter/src/widgets/framework.dart:941:6)
    #2      CarouselSliderState.getTimer.<anonymous closure> (package:carousel_slider/carousel_slider.dart:128:41)
    #3      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
    #4      _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
    #5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
    

    Checking prior if widget is mounted fixes this issue.

    opened by AurimasOutgrid 0
Releases(1.2.0)
  • 1.2.0(Mar 18, 2019)

    Introducing two new features, Vertical scroll and enable/disable infinite scroll .

    Pass an Axis as the scrollDirection argument to specify direction.
    Use enableInfiniteScroll to toggle between finite and infinite scroll mode. When enableInfiniteScroll is set to false the carousel will not scroll past the first or last item.

    Source code(tar.gz)
    Source code(zip)
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

FlutterCandies 1.5k Nov 30, 2022
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.

null 40 Nov 30, 2022
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)

Firgia 8 Nov 23, 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.

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

Fire Slime Games 1.7k Nov 28, 2022
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.

Mahdi 215 Nov 4, 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. Installation Add dependency to your pubspec.yaml

Anatoly Pulyaevskiy 270 Sep 29, 2022
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

Dan Field 1.5k Nov 26, 2022
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.

Chooyan 93 Nov 30, 2022
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

Sai Gokula Krishnan 36 Nov 28, 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

Paweł Wacławiak 0 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

7c00 3 Oct 5, 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 GIFs High quality Android and iOS loading spinners. View Demo Loading GIFs is a collection of high fidelity loading animations in GIF format.

Codelessly 30 Oct 25, 2022
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

HungHD 885 Nov 27, 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

Baseflow 2.1k Dec 1, 2022
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

Radoslav Vitanov 898 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

Cameron Smith 161 Nov 22, 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

路小飞 3 Jul 8, 2021
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.

Iheb Briki 70 Nov 18, 2022
Minimal Unsplash Android App to easily search and download images

Minimal Unsplash Android App to easily search and download images

Yash Garg 19 Aug 3, 2022