简体   繁体   中英

Timer.periodic flutter,

@override
void initState() {
 super.initState();

 bool isLastPage = (_currentPage.round() == sliderArrayList.length - 1 );

 //Trying to build automatic scrollable
 Timer.periodic(Duration(seconds: 5), (Timer timer) {
  if (_pageController.hasClients && !isLastPage) {
    _pageController.nextPage(
      duration: Duration(milliseconds: 200),
      curve: Curves.easeIn);}
  if(isLastPage){
    timer.cancel();
  }
 });
}

I am trying to build a periodic timer which scrolls pages in pageview, flutter after every 5 seconds, however it keeps on scrolling even after the last page. I have tried to implement the above method if(isLastPage){timer.cancel();} and it doesnt work.

You've to evaluate that expression everytime timer ticks. Also, Put the isLastPage check before the hasClients check.

Timer.periodic(Duration(seconds: 5), (Timer timer) {
  final isLastPage = _currentPage.round() == sliderArrayList.length - 1;
  if (isLastPage) {
    timer.cancel();
    return;
  }
  if (_pageController.hasClients) {
    _pageController.nextPage(
      duration: Duration(milliseconds: 200),
      curve: Curves.easeIn);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM