Search code examples
flutteranimationflutter-animationflutter-pageview

FLUTTER: PageView.builder onPage property - can i change so the index is triggered upon a FULL page swipe instead of 0.50


Using PageView.builder in Flutter, I have made a basic quiz with random repopulating questions, and some animation that I want to trigger every time a new page comes into view.

Also, of relevance, the user can only proceed to the next page once they have answered a question on each page. (Hence to control swiping, I created a ternary operator on the physics property where the onScroll boolean is set to false when the onPage method is triggered, (and changed back later by the user to true when they answer a question by pressing a button)).

So, everything is working well, except one annoying sideeffect:

The onPageChange property is "Called whenever the page in the center of the viewport changes." and the animation set for the new page, will play on the previous page as it dissapears from view, as the onState method needed for the onScroll boolean is triggered half way during the scroll causing a rebuild.

A simple fix would be if I could change the onPageChange property to trigger only once a FULL page swipe has been completed...but I cant work out how to achieve this..?

Thank you!


       @override
  Widget build(BuildContext context) {
    return Material(
        child: PageView.builder(
    
            onPageChanged: (int i) {

          print('page changed! + i');
          setState(() {_canScroll = false;});
      },
      physics: _canScroll
          ? AlwaysScrollableScrollPhysics()
          : NeverScrollableScrollPhysics(),
      pageSnapping: true,
      itemBuilder: (context, index) {
        _index = index;
        return WordCardWidget(
          word1: _word1,
          word2: _word2,
          answer: answer,
          animationType: _cardAnimType,
          buttonSelected: buttonSelected,
        );
      },
    ));
  }
}

Solution

  • Leaving this up, in case it helps any future readers.

    I got this to work by using itemCount property and incrementing with a local variable, hence I dont need to use the setState method on the onPage property. The users can progress through each page only after attemping to answer a question which increases the itemCount by one.

    (I have amended my original post where I wrongly thought this didnt work).

    Here is the relevant working code snippet for reference :)

    
           child: PageView.builder(
              itemCount: itemCount,
                onPageChanged: (int i) {
              print('page changed! + i');
          },