How to implement Carousel Slider in Flutter

As mobile developers, we sometimes have to create sliding, animated, background image carousels, but sometimes we require to create a sliding card carousel that contains some data with different background colors or gradients. In this guide, we will learn how to implement the Carousel Slider in a flutter. 

Carousel Slider is one of the most popular image sliders used nowadays in most apps. These are mostly seen on various eCommerce sites such as Amazon, Flipkart, Myntra, and many more. Displaying the images in a slider gives an attractive User Experience. As these sliders are automated you can get to see various types of images and content in them. 

Properties of Carousel Slider

Items declare Asset Images or Network Images that are used in our app
Optionsconsists of many properties such as
height: Overall height of card to display the image
autoplay: Cards automatically slide at a time
autoplaycurve: Determines the animation curve
aspectRatio: Aspect Ratio is used to declare the height
autoPlayAnimationDuration: Used to declare time for automated slide

To Implement the Carousel Slider in Flutter we have to follow the following steps:

First, add Carousel Slider dependency in pubspec.yaml file in the lib folder

We have added the dependency for Carousel Slider in our pubspec.yaml file located in the lib folder in dependencies as shown below:

carousel_slider: ^4.1.1

Let’s take an example of how we can implement the Carousel Slider in our flutter application.

we will create a new model name Fruit that includes the String of name description and the URL of that class name Fruit and store it into a new file inside the lib folder name fruit_model.dart.

class Fruit {
  String name, desc, url;
  Friut({
    required this.name,
    required this.desc,
    required this.url,
  });
}

Now we will again create a new file name as fruit_data.dart that includes the dummy data.

import 'package:vlogpost/model/student.dart';

List<Fruit> fruits = [
  Fruit(
      name: 'Apple',
      desc:
          'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the',
      url: 'assets/apple.jpg'),
  Fruit(
      name: 'Banana',
      desc:
          'banana is an elongated, edible fruit - botanically a berry - produced by several kinds of large herbaceous flowering plants in the genus Musa.',
      url: 'assets/banana.jpg'),
  Fruit(
      name: 'Grape',
      desc:
          'The grapefruit (Citrus × paradisi) is a subtropical citrus tree known for its relatively large, sour to semi-sweet, somewhat bitter fruit.',
      url: 'assets/grape.jpg'),
  Fruit(
      name: 'Mango',
      desc:
          'A mango is an edible stone fruit produced by the tropical tree Mangifera indica which is believed to have originated from the region between northwestern ...',
      url: 'assets/mango.jpg'),
  Fruit(
      name: 'Orange',
      desc:
          'An orange is a fruit of various citrus species in the family Rutaceae ); it primarily refers to Citrus × sinensis, which is also called sweet orange',
      url: 'assets/orange.jpg'),
  Fruit(
      name: 'WaterMelon',
      desc:
          'Watermelon is grown in favorable climates from tropical to temperate regions worldwide for its large edible fruit',
      url: 'assets/watermelon.jpg'),
  Fruit(
      name: 'Papaya',
      desc:
          'Papayas grow in tropical climates and are also known as papaws or pawpaws. Their sweet taste, vibrant color, and the wide variety of health benefits they ',
      url: 'assets/papaya.jpg'),
  Fruit(
      name: 'Coconut',
      desc:
          'A coconut is the edible fruit of the coconut palm (Cocos nucifera), a tree of the palm family. ',
      url: 'assets/coconut.jpg'),
];

In the above line of code, I have used the local image name as an assets folder to store the image of fruits. for these, I have taken different fruit images which are shown below.

The Next Step is to include the assets folder inside the pubspec. yaml which is shown below

# To add assets to your application, add an assets section, like this:
  assets:
    - assets/

Now let’s implement the code in the Flutter application.

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:vlogpost/data/food_data.dart';
import 'package:vlogpost/model/student.dart';

class ImageCarasoulScreen extends StatefulWidget {
  const ImageCarasoulScreen({Key? key}) : super(key: key);

  @override
  State<ImageCarasoulScreen> createState() => _ImageCarasoulScreenState();
}

class _ImageCarasoulScreenState extends State<ImageCarasoulScreen> {
  List<Fruit> fruit = [];
  @override
  void initState() {
    fruit = List.from(fruits);
    super.initState();
  }

  int _current = 0;
  final CarouselController _controller = CarouselController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text('Image Carasoul'),
        centerTitle: true,
      ),
      body: Column(children: [
        CarouselSlider(
          items: fruit
              .map(
                (e) => Container(
                  decoration: const BoxDecoration(color: Color(0xff262837)),
                  margin: const EdgeInsets.all(10),
                  child: ClipRRect(
                      borderRadius: const BorderRadius.all(Radius.circular(5)),
                      child: Stack(
                        children: <Widget>[
                          Image.asset(
                            e.url,
                            fit: BoxFit.cover,
                            width: double.infinity,
                          ),
                          Positioned(
                            bottom: 0,
                            left: 0,
                            right: 0,
                            child: Container(
                              decoration: const BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [
                                    Color.fromARGB(200, 0, 0, 0),
                                    Color.fromARGB(0, 0, 0, 0)
                                  ],
                                  begin: Alignment.bottomCenter,
                                  end: Alignment.topCenter,
                                ),
                              ),
                              padding: const EdgeInsets.symmetric(
                                  vertical: 10, horizontal: 20),
                              child: Text(
                                e.name,
                                style: Theme.of(context)
                                    .textTheme
                                    .headline6
                                    ?.copyWith(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                    ),
                              ),
                            ),
                          ),
                        ],
                      )),
                ),
              )
              .toList(),
          carouselController: _controller,
          options: CarouselOptions(
              autoPlay: true,
              enlargeCenterPage: true,
              aspectRatio: 2,
              onPageChanged: (index, e) {
                setState(() {
                  _current = index;
                });
              }),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: fruit.asMap().entries.map((data) {
            return GestureDetector(
              onTap: () => _controller.animateToPage(data.key),
              child: Container(
                width: 12,
                height: 12,
                margin: const EdgeInsets.symmetric(
                  vertical: 8,
                  horizontal: 4,
                ),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white
                      .withOpacity(_current == data.key ? 0.9 : 0.4),
                ),
              ),
            );
          }).toList(),
        ),
      ]),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thank you for reading the Guide about How to implement Carousel Slider in Flutter.

Also Read: How To Implement Onboarding Screen PageView In Flutter