按下后退按钮时如何在 PageView 中向后移动 [Flutter]

Rog*_*rin 5 flutter flutter-layout

我想在使用 pageView 按下后退按钮时向后移动,我阅读了 WillPopScope 组件,但我没有推/弹出另一个屏幕。我只是在 pageView 上移动不同的页面。

任何线索如何做到这一点?

此致。

Smi*_*ily 7

是的,您可以使用WillPopScope. 不确定这是否是最佳的,但它对我来说很完美;请记住,我希望后退按钮从其中一页到它之前的一页工作,而不是在所有页面上工作,但我确信该解决方案适用。

在页面中,我用WillPopScope这样包围了所有东西

return new WillPopScope(
  onWillPop: () => Future.sync(onWillPop),
  child: // Whatever your page was
Run Code Online (Sandbox Code Playgroud)

现在,您必须定义 proc onWillPop,在我的情况下就是这样

bool onWillPop() {
  _controller.previousPage(
    duration: Duration(milliseconds: 200),
    curve: Curves.linear,
  );
  return false;
}
Run Code Online (Sandbox Code Playgroud)

就我而言,这永远不会失败,因为它仅用于一种视图,而且仅用于一种视图。

在你的情况下,你可能想要这样的条件:

bool onWillPop() {
  if (_controller.page.round() == _controller.initialPage)
    return true;
  else {
    _controller.previousPage(
      duration: Duration(milliseconds: 200),
      curve: Curves.linear,
    );
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。有关覆盖后退按钮的一般参考,请参阅其他 StackOverFlowAnswer。

编辑:向我的 onWillPop 添加了一个返回值以删除飞镖警告。