Want to scroll or jump to position of PageView.builder or PageController in Flutter? You can use jumpTo() method to scroll position for PageView. I have create one changePageViewPostion() method in below example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import 'package:flutter/material.dart'; class MyPageView extends StatefulWidget { createState() { return StateKeeper(); } } class StateKeeper extends State<MyPageView> { PageController controller = PageController(viewportFraction: 1, keepPage: true); var currentPageValue = 0.0; var mItemCount = 10; @override void initState() { // TODO: implement initState super.initState(); controller.addListener(() { setState(() { currentPageValue = controller.page; }); }); } void changePageViewPostion(int whichPage) { if(controller != null){ whichPage = whichPage + 1; // because position will start from 0 double jumpPosition = MediaQuery.of(context).size.width / 2; double orgPosition = MediaQuery.of(context).size.width / 2; for(int i=0; i<mItemCount; i++){ controller.jumpTo(jumpPosition); if(i==whichPage){ break; } jumpPosition = jumpPosition + orgPosition; } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('PageView position change'), ), body: PageView.builder( controller: controller, itemBuilder: (context, position) { return Container( color: position % 2 == 0 ? Colors.blue : Colors.pink, child: Column( children: <Widget>[ Center( child: Text( "Page " + (position + 1).toString(), style: TextStyle(color: Colors.white, fontSize: 22.0), ), ), Align( alignment: FractionalOffset.bottomCenter, child: Padding(padding: EdgeInsets.only(bottom: 20), child: FloatingActionButton( elevation: 0.0, child: new Icon(Icons.check), backgroundColor: new Color(0xFFE57373), onPressed: (){ changePageViewPostion(5); } ),), ), ], ), ); }, itemCount: mItemCount, ) ); } } |
We can get current position with controller as below:
1 2 3 4 5 6 | controller.addListener(() { setState(() { currentPageValue = controller.page.toInt(); print((currentPageValue + 1).toString()); }); }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.