我正在尝试使用here
提供的这段代码现在,代码末尾有 2 个
IconButton
,多亏了它们,我们才能从一页移动到下一页(总共 3 页),它的工作原理如下:
但我不太喜欢这样,我希望它能这样工作:
愿意改变这一点,我将函数
IconButton
内的2OnPressed
的代码修改为:
//first IconButton
onPressed: () {
if (currentPageIndex == 0) {
onUpdateCurrentPageIndex(2);
} else {
onUpdateCurrentPageIndex(currentPageIndex - 1);
}
},
还有这个:
//second IconButton
onPressed: () {
if (currentPageIndex == 2) {
onUpdateCurrentPageIndex(0);
} else {
onUpdateCurrentPageIndex(currentPageIndex + 1);
}
},
现在它像我想要的那样工作,但是
TabPageSelector
(2 个箭头之间的 3 个点)有问题。
您可以自己尝试一下,点击我提供的链接并用我写的代码修改代码。
这是一种非常随机的行为,我不明白为什么,有人可以向我解释为什么会发生这种情况吗?以及我如何修复它。预先感谢!
问题出在
_updateCurrentPageIndex()
方法上。
方法内部有一个
.animateToPage
调用,它返回 Future<void>
(refs)。
void _updateCurrentPageIndex(int index) {
_tabController.index = index;
_pageViewController.animateToPage( // <- return the Future<void>
index,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
}
那么为什么你的点指示器移动得这么奇怪
是因为你同时改变了指示器位置和页面视图位置,但是
animateToPage()
需要等待一点时间才能完成,所以当点移动到目标位置时,它会再次移动到中间,因为目前浏览量位置仍然在中心。
解决方案很简单:
void _updateCurrentPageIndex(int index) async { // <- add async
await _pageViewController.animateToPage( // <- move this up and add await
index,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
_tabController.index = index; // <- move this below the animateToPage
}
async
关键字添加到方法中_tabController
的分配移至 animateToPage
调用下方await
关键字添加到 animateToPage
现在,点指示器将在
animateToPage
完成后移动。
希望能解决您的问题,谢谢😉