How to implement an Image Carousel slider in Flutter

Flutter Jul 30, 2023

Carousel sliders are popular user interface components that allow you to display a list of items in a scrollable, horizontal or vertical format. These can be used to showcase images, products, or any other content in an engaging and interactive manner. In this post, we will explore how to implement a carousel slider in Flutter using the carousel_slider package.

Installing

To get started, we need to install the carousel_slider package into our project. The installation process is simple. Just execute the following command: flutter pub add carousel_slider.

Once the command is executed, make sure to check your pubspec.yaml file for the added dependencies. You should see the carousel_slider package included in the dependencies section, like this:

dependencies:
  carousel_slider: ^4.2.1
  flutter:
    sdk: flutter

Implementation

Now that the package is installed let us go over the different ways to implement the carousel slider. In the examples below we will build carousels that display images. The images will be retrieved from Lorem Picsum which is a free online service that provides random placeholder images. The images will be displayed using the Image.network widget.

To start off we will implement a basic carousel slider using the CarouselSlider widget, see the code below:

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImageCarousel(),
    );
  }
}

class ImageCarousel extends StatelessWidget {
  final List<String> pictureUrls = List.generate(5, (index) {
    return 'https://picsum.photos/id/${index + 200}/300/200';
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Carousel'),
      ),
      body: Center(
        child: CarouselSlider(
          items: pictureUrls
              .map(
                (url) => Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.symmetric(horizontal: 5.0),
              child: Image.network(url, fit: BoxFit.cover),
            ),
          )
              .toList(),
          options: CarouselOptions(),
        ),
      ),
    );
  }
}

In this code snippet, we create a simple Flutter application with the CarouselSlider widget using the carousel_slider package. The carousel displays five images retrieved from Lorem Picsum with different IDs.

To display the carousel, we use the CarouselSlider widget, which takes a list of widgets (items) representing the carousel items. Each item in the carousel is represented by a Container widget containing an Image.network widget to display the retrieved image. The fit property of the Image.network is set to BoxFit.cover to ensure the image fills the container without distortion.

For customization, the carousel_slider package offers CarouselOptions, which can be used to configure features like auto-play, aspect ratio, scrolling direction, and more. In this snippet, we kept it simple and did not provide custom options.

flutter_carousel_slider_with_5_images

Instead of using the Carousel widget directly we can also use its builder, see the following example:

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImageCarousel(),
    );
  }
}

class ImageCarousel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Carousel'),
      ),
      body: Center(
        child: CarouselSlider.builder(
          itemCount: 5,
          itemBuilder: (context, index, realIndex) {
            return Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.symmetric(horizontal: 5.0),
              child: Image.network(
                'https://picsum.photos/id/${index + 210}/300/200',
                fit: BoxFit.cover,
              ),
            );
          },
          options: CarouselOptions(),
        ),
      ),
    );
  }
}

In this code snippet, we introduce a more dynamic approach to displaying the carousel items using the CarouselSlider.builder constructor. The constructor optimizes memory usage by dynamically generating and rendering carousel items only when they become visible on the screen, rather than pre-building all items upfront.

The itemCount property is set to 5, indicating that we want to show five images in the carousel. To show a difference between the GIF of the previous example, we retrieve different images from Lorem Picsum. Other than that we will have the same results as the previous implementation.

flutter_carousel_slider_with_5_images_using_builder

Full-screen images

With some minor changes it is also possible to display full screen images in the carousel, see the code below:

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImageCarousel(),
    );
  }
}

class ImageCarousel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Carousel'),
      ),
      body: Center(
        child: CarouselSlider.builder(
          itemCount: 5,
          itemBuilder: (context, index, realIndex) {
            return Container(
              width: MediaQuery.of(context).size.width,
              child: Image.network(
                'https://picsum.photos/id/${index + 200}/1000/1500',
                fit: BoxFit.cover,
              ),
            );
          },
          options: CarouselOptions(
            viewportFraction: 1,
            height: MediaQuery.of(context).size.height,
          ),
        ),
      ),
    );
  }
}

In this code snippet, we use the CarouselSlider.builder constructor to create a full screen image carousel. The Lorem Picsum image dimensions are increased to a width of 1000 and a height of 1500 to fill the entire screen, and we removed the margin property from the Container widget.

In the CarouselOptions, we set the viewportFraction property to 1, ensuring each image occupies the entire horizontal width of the carousel. Additionally, we set the height property to MediaQuery.of(context).size.height, enabling the images to span the entire screen vertically.

When the application is run, the carousel displays images that cover the entire width and height of the screen:

flutter_carousel_slider_with_5_images_on_full_screen

In addition to adjusting the height and width of carousel items, the CarouselOptions class offers many configuration options to customize the carousel. Let us go over some examples:

Enable auto-play to showcase content automatically without user interaction.

CarouselOptions(
  autoPlay: true,
  autoPlayInterval: Duration(seconds: 2),
  autoPlayAnimationDuration: Duration(milliseconds: 800),
  autoPlayCurve: Curves.fastOutSlowIn,
),

By using the autoPlay property along with autoPlayInterval, autoPlayAnimationDuration, and autoPlayCurve, we can enable smooth and automatic scrolling through the carousel items.

flutter_carousel_slider_with_5_images_with_autoplay

Enlarge center item

Highlight the center item in the carousel by making it larger than surrounding items.

CarouselOptions(
  enlargeCenterPage: true,
),

This can easily be achieved by setting enlargeCenterPage property to true .

flutter_carousel_slider_with_5_images_with_enlarged_center_image

Instead of using a horizontal carousel it is possible to change the direction to vertical.

CarouselOptions(
  scrollDirection: Axis.vertical,
),

By setting the scrollDirection property to Axis.vertical, you can change the default horizontal scrolling behavior of the carousel to vertical scrolling.

flutter_carousel_slider_with_5_images_with_vertical_scroll

Disabling infinite scroll

By disabling the infinite scrolling users will no longer experience endless scrolling, making it ideal for scenarios where a fixed number of items is preferred.

CarouselOptions(
  enableInfiniteScroll: false,
),

To achieve this set the enableInfiniteScroll property to false.

flutter_carousel_slider_with_5_images_without_infinite_scroll

Conclusion

In this post, we explored two ways to implement a carousel slider in Flutter using the carousel_slider package. You learned how to create basic carousels with the CarouselSlider widget and dynamic carousels with the CarouselSlider.builder constructor. We also went over possible configurations that can be made by setting certain properties in the CarouselOptions class.

Tags