Updated 29 April 2023
Carousel Slider is one of the most popular image sliders used nowadays in most apps. 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.
You may also explore our Flutter app development page.
To Implement the Carousel Slider in Flutter you have to follow the following steps:
1: First add Carousel Slider dependency in your pubspec.yaml file
1 2 3 4 |
dependencies: carousel_slider: ^4.0.0 |
2: Let’s move to the next part
Here we will create the class for our demo (In my case “MyHomePage” )
1 2 3 4 5 6 7 8 9 10 11 |
class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Carousel Demo'), ), body: Center(child: getSlider()), //===Will find the function in next step ); } } |
3: In this step, we will set up our slider according to our needs
In my case, I have used a simple container with a center align text field.
Note:- This is just a demo code you can modify this according to your needs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Widget getSlider() { return CarouselSlider( options: getOptions(), //=====Find the options in next step 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: const BoxDecoration(color: Colors.amber), child: Center( child: Text( 'text $i', style: const TextStyle(fontSize: 16.0), ), )); }, ); }).toList(), ); } |
4: In this step, we will set up our slider options
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
CarouselOptions getOptions() { return CarouselOptions( height: 400, aspectRatio: 16 / 9, viewportFraction: 0.8, initialPage: 0, enableInfiniteScroll: true, reverse: false, autoPlay: true, autoPlayInterval: const Duration(seconds: 3), autoPlayAnimationDuration: const Duration(milliseconds: 800), autoPlayCurve: Curves.fastOutSlowIn, enlargeCenterPage: true, onPageChanged: (position, reason){ print("Current Position:- $position"); print("Change Reason:- ${reason.name}"); }, scrollDirection: Axis.horizontal, ); } |
Now, we are ready to try this
As a result, you will get the 5 sliding cards on the center of your screen
Check the given video for output
To know more about carousel_slider please check this link
You can also check some examples from this link
Note:- For a better user experience, please use a mobile device to open this carousel slider example link.
Hopefully, this blog will be helpful to you to understand the Carousel Slider. If you have any queries, please write them in the comment section.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.