flutter carousel example with indocator

In this tutorial i’m gonna show to you how to create image slider using Carousel in Flutter.

Table of Contents

Introduction

As a developer, you might design app with sliding image, image carousel and other slider in app or website. So when you develop your app using flutter, you may need to this plugin carousel_silder.

Carousel Slider

Carousel slider is support infinite scroll and custom child widget, it was published Apr 17, 2020 with the first version 0.0.1 and the latest version 2.0.0 on Apr 16, 2020. You can learn basic instruction in this link.

Let’s get started…!!!

Firstly, we need to import the plugin package into pubspec.yaml file, add this code under dependencies.

dependencies:
  flutter:
    sdk: flutter
  carousel_slider: ^2.0.0

Second, after we import the plugin then create new file CarouselExample.dart, add this line code in the first line to import package carousel_slider.

import 'package:carousel_slider/carousel_slider.dart';

Next, define variable image that we want to show as image slider in List variable.

List imgNews = [
    "lib/images/header-1.jpg",
    "lib/images/header-2.jpg",
    "lib/images/header-3.jpg",
    "lib/images/header-4.jpg",
];

After that, we need a function to looping that list and mapping into new list, so lets create function here.

List<T> map<T>(List list, Function handler) {
    List<T> result = [];
    for (var i = 0; i < list.length; i++) {
      result.add(handler(i, list[i]));
    }
    return result;
  }

Once you done create image list and image list mapping function, now we need to create widget to showing the images, as i mentioned before, we use carousel as slider image so lets create widget CarouselSlider in build section,

@override
  Widget build(BuildContext context) {
    return CarouselSlider(
      options: CarouselOptions(
        autoPlay: true,
        height: 250,
        viewportFraction: 1.0,
        onPageChanged: (index, reason) {
          setState(() {
          });
        },
      ),
      items: imgNews.map(
        (url) {
        return Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              ClipRRect(
                child: Image.asset(
                  url,
                  fit: BoxFit.fill,
                  height: 250,
                ),
                ),
              ],
              ) 
            );
          },
      ).toList(),   
    );
  }

As you can see, in code above, there is options attribute, that attribute have a function to setting our slider, it implement CarouselOptions, you can adjust you carousel setting there, check this link to learn more about CaourselOptions.

Carousel Option

CarouselSlider(
   items: items,
   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,
      pauseAutoPlayOnTouch: Duration(seconds: 10),
      enlargeCenterPage: true,
      onPageChanged: callbackFunction,
      scrollDirection: Axis.horizontal,
   )
 )

In items there, the images list will automatically show after we mapping with function that already declare.

Finally, let’s run project.

flutter carousel example

You will see image slider is running well.

Unfortunately, we don’t have indicator for image slider there, yet. So let’s just create indicator to inform us where is the position of the image running.

Let’s wrap carousel into widget column, and also add widget row for indicator image slider.

Carousel Widget

int _current = 0;
Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CarouselSlider(
          options: CarouselOptions(
            autoPlay: true,
            height: 250,
            viewportFraction: 1.0,
            onPageChanged: (index, reason) {
              setState(() {
                _current = index;
              });
            },
          ),
          items: imgNews.map(
            (url) {
            return Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  ClipRRect(
                    child: Image.asset(
                      url,
                      fit: BoxFit.fill,
                      height: 250,
                    ),
                    ),
                  ],
                  ) 
                );
              },
          ).toList(),      
        ),
        Padding(
          padding: EdgeInsets.only(top:10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: map<Widget>(imgNews, (index, url) {
              return Container(
                width: 6.0,
                height: 8.0,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index ? Colors.red : Colors.blueGrey,
                ),
              );
            }),
          ),
        ),
      ]
    );
  }

If you notice that, you will see a new variable _current declared there. That’s variable we use for store the current state of image slider on onPageChange event.

onPageChanged: (index, reason) {
  setState(() {
    _current = index;
  });
},

Let’s running project again then you will see indicator below image slider.

flutter carousel example indicator

Now we have indicator slider. You might notice some apps put indicator inside image, and you want to put it there too, you can do that by wrap them in Stack widget and give padding the position for indicator.

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

class CarouselExample extends StatefulWidget{
  const CarouselExample({ Key key }) : super(key: key);
  @override
   _CarouselExampleState createState() =>  _CarouselExampleState();
}


class _CarouselExampleState extends State<CarouselExample>  {
  List imgNews = [
    "lib/images/header-1.jpg",
    "lib/images/header-2.jpg",
    "lib/images/header-3.jpg",
    "lib/images/header-4.jpg",
  ];

  @override
  void initState() {
    super.initState();

  }

  List<T> map<T>(List list, Function handler) {
    List<T> result = [];
    for (var i = 0; i < list.length; i++) {
      result.add(handler(i, list[i]));
    }
    return result;
  }

  
  int _current = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Stack(
          children: [
            CarouselSlider(
              options: CarouselOptions(
                autoPlay: true,
                height: 250,
                viewportFraction: 1.0,
                onPageChanged: (index, reason) {
                  setState(() {
                    _current = index;
                  });
                },
              ),
              items: imgNews.map(
                (url) {
                return Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      ClipRRect(
                        child: Image.asset(
                          url,
                          fit: BoxFit.fill,
                          height: 250,
                        ),
                        ),
                      ],
                      ) 
                    );
                  },
              ).toList(),
              
            ),
            Padding(
              padding: EdgeInsets.only(top:210),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: map<Widget>(imgNews, (index, url) {
                  return Container(
                    width: 6.0,
                    height: 8.0,
                    margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _current == index ? Colors.red : Colors.blueGrey,
                    ),
                  );
                }),
              ),
            ),    
          ],
        )
      ]
    );
  }  
}

Save file and you will see indicator move to inside image.

flutter carousel example indicator image

Congratulation, now you have beauty image slider.

In conclusion, through this tutorial you have been learn about how to create image slider using carousel_slider plugin.

Hope this tutorial will help you.

For more tutorial about flutter, you can visit this link.

Advertisements
Share: