Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get from index in PageView onPageChanged in Flutter?

How do I get the previous index in PageView onPageChanged? Currently, I can get the current index when the page changes with the following code:

PageView(
      children: <Widget>[
        SomeView(),
        SomeOtherViews(),
        SomeOtherViews(),
      ],
      controller: _pageViewController,
      onPageChanged: _onPageViewChange,
    );

_onPageViewChange(int page) {   
    print("Current Page: " + page.toString());
  }

Does flutter have any built-in function for this? Or should I just manually save the page as reference for the previous page?

  • Yes I have thought of that, I just want to know if there's a faster way without having to create a variable
like image 649
Rick Avatar asked Mar 27 '19 16:03

Rick


People also ask

What is PageView builder in flutter?

Creates a scrollable list that works page by page using widgets that are created on demand. This constructor is appropriate for page views with a large (or infinite) number of children because the builder is called only for those children that are actually visible.


1 Answers

Decrement page by 1 and store in a class Variable (call setState & modify) or local variable. If current-page is 0 set previousPage to totalPageCount - 1.

_onPageViewChange(int page) {   
  print("Current Page: " + page.toString());
  int previousPage = page;
  if(page != 0) previousPage--;
  else previousPage = 2;
  print("Previous page: $previousPage");
}
like image 96
Tirth Patel Avatar answered Oct 07 '22 16:10

Tirth Patel