How to create an image slider in Flutter
Flutter provides creative freedom to developers to create visually attractive applications by providing a variety of UI features. Flutter is a single codebase framework that can be used across different platforms like Android and iOS. It has pub package manager that offers a range of packages and plugins.
What is an image slider?
An image sider refers to a carousel of images that shows a set of images one by one when slid towards right or left without changing the webpage. The images are placed in a series to form a gallery where one picture is visible at one moment in order to improve the user's focus on one image and its content. We can use dots or arrows to make navigation easier from one image to the other.
Let's code this feature and make a small application in Flutter.
Example code
In this example, we make an image slider that dynamically changes the images as we slide through them and use dots to show the current image position in the gallery.
import 'package:flutter/material.dart';
void main() {
runApp(ImageSliderApp());
}
class ImageSliderApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ImageSliderScreen(),
);
}
}
class ImageSliderScreen extends StatefulWidget {
@override
_ImageSliderScreenState createState() => _ImageSliderScreenState();
}
class _ImageSliderScreenState extends State<ImageSliderScreen> {
PageController _pageController = PageController();
int _currentPage = 0;
List<String> _images = [
'https://images.pexels.com/photos/6889088/pexels-photo-6889088.jpeg?auto=compress&cs=tinysrgb&w=1600',
'https://images.pexels.com/photos/10643964/pexels-photo-10643964.jpeg?auto=compress&cs=tinysrgb&w=600',
'https://images.pexels.com/photos/7780128/pexels-photo-7780128.jpeg?auto=compress&cs=tinysrgb&w=1600',
'https://images.pexels.com/photos/7573942/pexels-photo-7573942.jpeg?auto=compress&cs=tinysrgb&w=1600',
'https://images.pexels.com/photos/3390587/pexels-photo-3390587.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load'
];
@override
void initState() {
super.initState();
_pageController.addListener(() {
setState(() {
_currentPage = _pageController.page!.round();
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Aesthetic Image Slider'),
centerTitle: true,
),
body: Stack(
alignment: Alignment.bottomCenter,
children: [
PageView.builder(
controller: _pageController,
itemCount: _images.length,
itemBuilder: (context, index) {
return Image.network(
_images[index],
fit: BoxFit.cover,
);
},
),
Positioned(
bottom: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: _buildPageIndicator(),
),
),
],
),
);
}
List<Widget> _buildPageIndicator() {
List<Widget> indicators = [];
for (int i = 0; i < _images.length; i++) {
indicators.add(
Container(
width: 10,
height: 10,
margin: EdgeInsets.symmetric(horizontal: 5),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentPage == i ? Colors.blue : Colors.grey,
),
),
);
}
return indicators;
}
}Note: Slide the cursor to the left for viewing the image on the right and slide the cursor to the right for viewing the image on the left.
Code explanation
Lines 1–4: Import the required packages and define the main by sending an instance of
ImageSliderAppto therunApp()method.Line 7: Define the
ImageSliderAppclass that extends theStatelessWidgetclass to access its methods and attributes.Lines 9–11: Override the
buildmethod and return aMaterialAppand set thehomeproperty toImageSliderScreen().
Lines 16–18: Define the
ImageSliderScreen()class that extends theStatefulWidgetclass and create a_ImageSliderScreenState()instance.Lines 21–23: Define the
_TodoListScreenState()class that representsImageSliderScreenstate and hold aPageControllerinstance.
Lines 34–35: Create a list object
_imagesthat contains the URLs of all the images that will be displayed in the image slider. We can add local files by adding their correct directory path and names.Lines 25–32: Override the
initState()method that initializes the state of the widget when it is created.Lines 36–38: Add a listener on
_pageControllerto keep track of the pages and save the current page on the_currentPageattribute.Lines 44–45: Create the app UI in the
buildmethod that returns aScaffoldwidget containing the basic structure.Lines 46–48: Set the
appBarproperty to anAppBarwidget, which specifies the atitleand thebackgroundColor.Lines 50–56: Create a
Stackin thebodyand add aPageView.builderwidget that dynamically generates pages for each image instance in the list.Lines 57–59: Return an
Image.networkwidget that fetches the image from the specified URL and displays it in the given page space.
Lines 63–67: Add a
Positionwidget to set the placement of the image dots on the screen; in this case they are placed in the bottom center, which dynamically changes through_buildPageIndicator()method.Lines 75–85: Define the
_buildPageIndicator()method that uses a for loop to generate the dots based on the total number of images as and the current image.
Code output
Slide the images to the left or right and notice that the images change, and according to the current image, the dots in the bottom center also dynamically change to show which picture number we are on at each slide. The dot turns blue to highlight the position.
Real-life application
There are a lot of real-life scenarios where we can use an image slider to present our content. Let's take a look at a few of the scenarios where image sliders are useful.
Summary
Flutter is a user friendly framework that helps the developers to create cross-platform applications with an attractive user interface. We can create different widgets and assign them functionalities to create a responsive application.
Note: Learn more about Flutter in the following Answers:
Free Resources