Image Carousel
Loading preview
Starting the Flutter app
A showcase of Flutter's image carousel functionality
import 'package:flutter/material.dart';
class ImageCarousel extends StatefulWidget {
const ImageCarousel({super.key});
@override
State<ImageCarousel> createState() => _ImageCarouselState();
}
class _ImageCarouselState extends State<ImageCarousel> {
final _pageController = PageController();
var _currentPage = 0;
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Gallery')),
body: Column(
children: [
Expanded(
child: PageView.builder(
controller: _pageController,
onPageChanged: (i) => setState(() => _currentPage = i),
itemCount: 5,
itemBuilder: (context, i) {
return Container(
margin: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.primaries[i % Colors.primaries.length]
.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(16),
),
child: Icon(
Icons.image,
size: 64,
color: Colors.white.withValues(alpha: 0.8),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(5, (i) => Container(
margin: const EdgeInsets.symmetric(horizontal: 4),
width: _currentPage == i ? 24 : 8,
height: 8,
decoration: BoxDecoration(
color: _currentPage == i
? Theme.of(context).colorScheme.primary
: Colors.grey[400],
borderRadius: BorderRadius.circular(4),
),
)),
),
),
],
),
);
}
}
Add it to your project
Copies the Dart source into your app, so you own it. Flutter SDK only, no extra packages.
First time? Run dart pub global activate fluttertemplates_dev, or read the CLI guide.
How it works
PageView.builder shows five tinted placeholders, and onPageChanged stores _currentPage so the active dot widens from 8px to 24px. Dots are plain Containers, so the width snaps rather than animates. The count of 5 is repeated in itemCount and List.generate, and dispose releases _pageController.
Adapting it
- Use a list of image URLs and drive both
itemCountandList.generatefrom its length. - Swap the dot
ContainerforAnimatedContainerto smooth the transition.