flutter_carousel_slider

repository·master·Indexed 23 days ago

https://github.com/serenader2014/flutter_carousel_slider

A versatile Flutter carousel slider widget supporting infinite scrolling, auto-play, and on-demand item building. It includes the CarouselSlider widget, CarouselOptions for configuration, and CarouselSliderController for programmatic navigation and autoplay management. Supports various enlargement strategies via CenterPageEnlargeStrategy and memory-efficient item building through CarouselSlider.builder.

Tokens
3.4K
Snippets
8
Records
20
Agent score
80%

What's inside carousel_slider

  1. Manually control the carousel with CarouselSliderController

    master

    To programmatically control the carousel (e.g., via buttons), create an instance of CarouselSliderController and pass it to the carouselController property of the CarouselSlider widget.

    class CarouselDemo extends StatelessWidget {
      CarouselSliderController buttonCarouselController = CarouselSliderController();
    
     @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('→'),
          )
        ]
      );
    }
  2. Use CenterPageEnlargeStrategy to customize page enlargement

    master

    When enlargeCenterPage is enabled in CarouselOptions, you can use the enlargeStrategy property to define how the center page is visually emphasized relative to its neighbors.

    Available strategies:

    • CenterPageEnlargeStrategy.scale: Scales the center page (default).
    • CenterPageEnlargeStrategy.height: Adjusts the height of the center page.
    • CenterPageEnlargeStrategy.zoom: Zooms the center page.
  3. Use the CarouselSlider widget

    master

    To create a basic carousel, instantiate the CarouselSlider widget. You must provide a list of items and a CarouselOptions object to configure the behavior and appearance. Note that since version 2.0.0, all configuration must be passed through CarouselOptions.

    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(),
    )
  4. Use CarouselSliderController methods

    master

    The CarouselSliderController provides several methods to manipulate the carousel position:

    • nextPage({Duration duration, Curve curve}): Animates to the next page.
    • previousPage({Duration duration, Curve curve}): Animates to the previous page.
    • jumpToPage(int page): Immediately jumps to the specified page index.
    • animateToPage(int page, {Duration duration, Curve curve}): Animates to the specified page index.
  5. Build item widgets on demand with CarouselSlider.builder

    master

    To optimize memory usage, use CarouselSlider.builder. This method builds items only when they are about to become visible on screen. This is ideal for large lists or content-heavy items.

    CarouselSlider.builder(
      itemCount: 15,
      itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) =>
        Container(
          child: Text(itemIndex.toString()),
        ),
    )
  6. Configure Carousel behavior with CarouselOptions

    master

    Use the CarouselOptions class to customize the appearance, scrolling behavior, and auto-play settings of a CarouselSlider.

    Key configuration categories include:

    Dimensions and Layout

    • height: Sets a fixed height for the carousel (overrides aspectRatio).
    • aspectRatio: The ratio used if no height is provided (defaults to 16/9).
    • viewportFraction: The fraction of the viewport each page occupies (defaults to 0.8).
    • padEnds: If true, adds padding to the start and end of the list so the first/last items are centered (only effective if viewportFraction < 1.0).
    • scrollDirection: The axis of scrolling (Axis.horizontal or Axis.vertical).

    Auto-play Settings

    • autoPlay: Enables or disables automatic sliding.
    • autoPlayInterval: Frequency of slides (defaults to 4 seconds).
    • autoPlayAnimationDuration: Duration of the transition animation (defaults to 800 ms).
    • autoPlayCurve: The animation curve (defaults to Curves.fastOutSlowIn).
    • pauseAutoPlayOnTouch: If true, auto-play pauses while the user is interacting with the carousel.
    • pauseAutoPlayOnManualNavigate: If true, auto-play pauses when using a CarouselSliderController to navigate.
    • pauseAutoPlayInFiniteScroll: If enableInfiniteScroll is false, determines if auto-play should pause at the last item (true) or loop back to the first (false).

    Visual Effects and Page Centering

    • enlargeCenterPage: If true, the current center page is larger than side images.
    • enlargeStrategy: Determines how the center page is enlarged (CenterPageEnlargeStrategy.scale, .height, or .zoom).
    • enlargeFactor: How much side pages are scaled down (defaults to 0.3).
    • disableCenter: If true, disables the Center widget for each slide.

    Scrolling and Interaction

    • enableInfiniteScroll: Whether the carousel loops infinitely.
    • animateToClosest: Whether to animate to the closest page occurrence.
    • pageSnapping: Enables or disables page snapping (defaults to true).
    • scrollPhysics: Custom ScrollPhysics for the carousel.

    Callbacks

    • onPageChanged: Triggered when the center page changes. Provides the index and a CarouselPageChangedReason (timed, manual, or controller).
    • onScrolled: Triggered whenever the carousel is scrolled, providing the scroll offset.
  7. Configure CarouselOptions

    master

    Use CarouselOptions to control the carousel's behavior.

    Important: If you provide a height parameter, the aspectRatio parameter will be ignored.

    Available configuration properties include:

    • height: Fixed height of the carousel.
    • aspectRatio: Aspect ratio of the carousel (ignored if height is set).
    • viewportFraction: Fraction of the viewport to display (e.g., 0.8).
    • initialPage: The starting page index.
    • enableInfiniteScroll: Whether the carousel loops infinitely.
    • reverse: Whether the carousel scrolls in reverse.
    • autoPlay: Whether the carousel automatically scrolls.
    • autoPlayInterval: Duration between auto-play transitions.
    • autoPlayAnimationDuration: Duration of the auto-play animation.
    • autoPlayCurve: The curve used for auto-play animations.
    • enlargeCenterPage: Whether to enlarge the center item.
    • enlargeFactor: The factor by which the center item is enlarged.
    • onPageChanged: Callback function triggered when the page changes.
    • scrollDirection: The axis of scrolling (Axis.horizontal or Axis.vertical).
    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,
          enlargeFactor: 0.3,
          onPageChanged: callbackFunction,
          scrollDirection: Axis.horizontal,
       )
     )
  8. Use CarouselSlider with a list of widgets

    master

    To create a carousel using a pre-defined list of widgets, use the default CarouselSlider constructor. You must provide a list of items and a CarouselOptions object to configure the behavior.

    CarouselSlider(
      items: [ 
        Text('Item 1'), 
        Text('Item 2'), 
        Text('Item 3'),
      ],
      options: CarouselOptions(
        height: 400.0,
        aspectRatio: 16/9,
        viewportFraction: 0.8,
        enlargeCenterPage: true,
      ),
    )
  9. Use CarouselSlider.builder for on-demand item building

    master

    For large lists or dynamic data, use the CarouselSlider.builder constructor. This approach builds items on demand using an itemBuilder, which is more memory-efficient than providing a full list of widgets.

    The itemBuilder follows the ExtendedIndexedWidgetBuilder signature: Widget Function(BuildContext context, int index, int realIndex)

    • index: The index of the item relative to the current view (can be affected by infinite scroll).
    • realIndex: The actual index of the item in the data source, useful for coordinating with Hero widgets.
    CarouselSlider.builder(
      itemCount: 10,
      itemBuilder: (context, index, realIndex) {
        return Text('Item $realIndex');
      },
      options: CarouselOptions(
        height: 400.0,
        enlargeCenterPage: true,
      ),
    )