我正在尝试通过使用PageView来获取哪个方向(左或右)用户滑动。我得到了这样的方向。
代码:
PageController _controller;
@override
void initState() {
_controller = new PageController()..addListener(_listener);
super.initState();
}
_listener() {
if (_controller.position.userScrollDirection == ScrollDirection.reverse) {
print('swiped to right');
} else {
print('swiped to left');
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: PageView.builder(
itemCount: 10,
controller: _controller,
itemBuilder: (context, index) {
return new Center(child: Text('item ${++index}'));
}),
);
}但是,由于滚动还没有结束,所以print方法返回了很多次。在当前页面完全切换到下一页之后,有什么方法可以让我得到这个吗?
颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动 颤振:向右滑动
发布于 2018-09-06 13:55:50
将当前_controller.page.round()与来自上一个侦听器调用的值进行比较(将前一个值存储在State中)。
发布于 2019-12-12 21:28:24
更好的解决方案如下,使用PageView小部件的内置函数。
PageView(
onPageChanged: (int page) {
// this page variable is the new page and will change before the pageController fully reaches the full, rounded int value
var swipingRight = page > pageController.page;
print(swipingRight);
},发布于 2020-09-19 16:53:10
这里没有一个解决方案对我有效,弄清楚这是一个令人头痛的问题。
最后,我使用了一个手势检测器,完全禁用了PageView手势。
NeverScrollableScrollPhysics()是如何禁用页面视图的内置手势的。
class MyPageView extends StatefulWidget {
@override
_MyPageViewState createState() => _MyPageViewState();
}
class _MyPageViewState extends State<MyPageView> {
PageController _pageController;
Duration pageTurnDuration = Duration(milliseconds: 500);
Curve pageTurnCurve = Curves.ease;
@override
void initState() {
super.initState();
// The PageController allows us to instruct the PageView to change pages.
_pageController = PageController();
}
void _goForward() {
_pageController.nextPage(duration: pageTurnDuration, curve: pageTurnCurve);
}
void _goBack() {
_pageController.previousPage(
duration: pageTurnDuration, curve: pageTurnCurve);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
// Using the DragEndDetails allows us to only fire once per swipe.
onHorizontalDragEnd: (dragEndDetails) {
if (dragEndDetails.primaryVelocity < 0) {
// Page forwards
print('Move page forwards');
_goForward();
} else if (dragEndDetails.primaryVelocity > 0) {
// Page backwards
print('Move page backwards');
_goBack();
}
},
child: PageView.builder(
itemCount: 10,
controller: _pageController,
// NeverScrollableScrollPhysics disables PageView built-in gestures.
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return new Center(child: Text('item ${++index}'));
}),
),
);
}
}https://stackoverflow.com/questions/52203527
复制相似问题