Skip to content

Instantly share code, notes, and snippets.

@Angeloem
Created September 20, 2021 20:07
Show Gist options
  • Save Angeloem/dec851c293d7614d92c61c36d81531b1 to your computer and use it in GitHub Desktop.
Save Angeloem/dec851c293d7614d92c61c36d81531b1 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'image.dart';
class ImageCarousel extends StatefulWidget {
final List images;
const ImageCarousel({Key? key, required this.images}) : super(key: key);
@override
_ImageCarouselState createState() => _ImageCarouselState();
}
class _ImageCarouselState extends State<ImageCarousel> {
PageController pageController = PageController();
Size get size => MediaQuery.of(context).size;
List uniqueImages = [];
@override
void initState() {
super.initState();
pageController.addListener(() {
setState(() {});
});
// we are using this so as to succumb to the problem that dart gives us, i.e no indexing while mapping,
// with this, we can get the final length hence index of the images
// plus we are using pageView which does not allow for changing children after building
uniqueImages = Set.from(widget.images).toList();
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
PageView(
reverse: false,
controller: pageController,
children: [
...uniqueImages.map((image) => Container(
width: size.width,
// you can use any image widget here, i am using cached_network_image
child: cachedImage(image),
)),
],
),
Positioned(
bottom: 20,
width: size.width,
child: Center(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...uniqueImages.map((image) => FutureBuilder(
future: Future.delayed(Duration.zero),
builder: (context, snapshot) {
double width = 10;
if (pageController.hasClients) {
if (uniqueImages.indexOf(image) == pageController.page!.toInt()) {
width = 30;
}
}
return Container(
height: 10,
width: width,
margin: EdgeInsets.symmetric(horizontal: 2.0),
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10)),
);
}))
],
),
),
),
)
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment