I've made a PageView that acts as an image carousel. How do I let it scroll automatically between its pages infinitely after some delay in Flutter?
new PageView(
children: List<Widget> {
new Container(
decoration: BoxDecoration(
image: DecorationImage(image: new AssetImage(images[0]),
fit: BoxFit.cover
)
)
),
new Container(
decoration: BoxDecoration(
image: DecorationImage(image: new AssetImage(images[1]),
fit: BoxFit.cover
)
)
),
new Container(
decoration: BoxDecoration(
image: DecorationImage(image: new AssetImage(images[2]),
fit: BoxFit.cover
)
)
)
}
)
You need to add a PageController
to your PageView
. Then on initState()
you can start a Timer.periodic()
where you just jump from page to page. Like this:
Note: You have to cancel the timer when dispose the page or other events.
int _currentPage = 0;
Timer _timer;
PageController _pageController = PageController(
initialPage: 0,
);
@override
void initState() {
super.initState();
_timer = Timer.periodic(Duration(seconds: 5), (Timer timer) {
if (_currentPage < 2) {
_currentPage++;
} else {
_currentPage = 0;
}
_pageController.animateToPage(
_currentPage,
duration: Duration(milliseconds: 350),
curve: Curves.easeIn,
);
});
}
@override
void dispose() {
super.dispose();
_timer?.cancel();
}
@override
Widget build(BuildContext context) {
return PageView(
controller: _pageController,
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: new AssetImage(images[0]),
fit: BoxFit.cover,
),
),
),
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: new AssetImage(images[1]),
fit: BoxFit.cover,
),
),
),
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: new AssetImage(images[2]),
fit: BoxFit.cover,
),
),
),
],
);
}
By the way you need to import 'dart:async'
for using Timer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With