How to get from index in PageView onPageChanged in Flutter?
Asked Answered
H

2

23

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
Heriberto answered 27/3, 2019 at 16:19 Comment(0)
M
24

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");
}
Midwinter answered 27/3, 2019 at 16:45 Comment(0)
C
6

You can use PageView.builder, it will give you page index.

PageView.builder(
  itemBuilder: (context, index) {
    // index gives you current page position.
    return _buildPage();
  },
  itemCount: listItemCount, // Can be null
)
Coulometer answered 27/3, 2019 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.