How to Create a Carousel Slider Widget in Flutter

Jun 23, 2022 | Programming

A carousel slider is a great way to display multiple items in a limited space, allowing users to swipe through content seamlessly. In this article, we will walk you through how to implement a carousel slider widget in a Flutter application. With features like infinite scrolling, custom child widgets, and auto-play, creating a visually engaging experience is straightforward!

Features of Carousel Slider

  • Infinite scroll
  • Custom child widgets
  • Auto play

Supported Platforms

  • Flutter Android
  • Flutter iOS
  • Flutter Web
  • Flutter Desktop

Live Preview

For a live preview of the carousel slider, check out the demo available at this link. For an optimal experience, it is recommended to view the demo on a mobile device.

Installation

To get started, you will need to add the carousel_slider dependency in your pubspec.yaml file. Here’s how you can do it:

dependencies:
  carousel_slider: ^5.0.0

Next, import the package in your Dart file:

import 'package:carousel_slider/carousel_slider.dart';

How to Use the Carousel Slider

Creating a CarouselSlider is simple. The idea is to create a CarouselSlider widget and pass the required parameters. Think of building a carousel slider similar to organizing a bookshelf:

  • You have several books (items) to display.
  • Each book rests on a shelf (container) that provides its own color and size.
  • The shelf can scroll infinitely, allowing readers to flip through the books at their leisure.

Basic Usage Example

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('Item $i', style: TextStyle(fontSize: 16.0)),
        );
      },
    );
  }).toList(),
)

Parameterized Carousel Slider

Here’s how you can customize further using parameters:

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

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

Building Item Widgets on Demand

This method saves memory by building items only when necessary, similar to ironing clothes—you only do it right before wearing them. Here’s an example:

CarouselSlider.builder(
  itemCount: 15,
  itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) {
    return Container(
      child: Text(itemIndex.toString()),
    );
  },
)

Controlling the Carousel Slider

To manually control the carousel’s position, you can use a CarouselSliderController. This allows you to go to the next or previous items programmatically, much like a remote control for your TV!

class CarouselDemo extends StatelessWidget {
  CarouselSliderController buttonCarouselController = CarouselSliderController();
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        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('→'),
        ),
      ],
    );
  }
}

CarouselSliderController Methods

Here are some useful methods available in the CarouselSliderController:

  • .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 specified page.
  • .animateToPage(int page, Duration duration, Curve curve) – Animate to the specified page.

Troubleshooting Tips

If you run into any issues while incorporating the Carousel Slider, consider the following troubleshooting tips:

  • Ensure you have added the correct version of carousel_slider in your dependencies.
  • Check for misspellings in the import statement or package name.
  • Look out for conflicts with other packages or dependencies in your pubspec.yaml file.
  • Ensure your layout constraints are not conflicting with the carousel’s dimensions.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Final Thoughts

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Conclusion

Embracing the carousel slider widget in your Flutter application can greatly enhance user experience. With customizable features and easy navigation, we hope this guide empowers you to implement a stunning carousel in your projects.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox