Flutter 中的滑动表单步骤?

HTM*_*ell 7 dart flutter

我正在 Flutter 中创建一个注册表单,我希望用户完成步骤。每一步都应该以滑动效果过渡到下一步。例如,如果我在第 1 步,移动到第 2 步应该将表单向左滑动,我应该得到表单 2。然后如果我回到表单 1,它应该向右滑动表单。

这是一个插图: 在此处输入图片说明

我试图用多条路线做到这一点:

routes: {
    '/': (context) => HomePage(),
    '/step1': (context) => FormStep1(),
    '/step2': (context) => FormStep2(),
},
Run Code Online (Sandbox Code Playgroud)

然后提交:

Navigator.push(
    context,
    EnterExitRoute(exitPage: FormStep1(), enterPage: FormStep2())
);
Run Code Online (Sandbox Code Playgroud)

进出路线

但这也会使 App Bar 滑动,我只希望表单滑动。

HTM*_*ell 11

在朋友的建议下,我最终使用了PageView. 这样我就不必为每一步都制作一条新路线。

class _RegisterFormState extends State<RegisterForm> {
  final _formsPageViewController = PageController();
  List _forms;


  @override
  Widget build(BuildContext context) {
    _forms = [
      WillPopScope(
        onWillPop: () => Future.sync(this.onWillPop),
        child: Step1Container(),
      ),
      WillPopScope(
        onWillPop: () => Future.sync(this.onWillPop),
        child: Step2Container(),
      ),
    ];

    return Expanded(
      child: PageView.builder(
        controller: _formsPageViewController,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return _forms[index];
        },
      ),
    );
  }

  void _nextFormStep() {
    _formsPageViewController.nextPage(
      duration: Duration(milliseconds: 300),
      curve: Curves.ease,
    );
  }

  bool onWillPop() {
    if (_formsPageViewController.page.round() ==
        _formsPageViewController.initialPage) return true;

    _formsPageViewController.previousPage(
      duration: Duration(milliseconds: 300),
      curve: Curves.ease,
    );

    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

解释:

  • 我用WillPopScope“后退”按钮包装每个表单会影响导航。
  • physics: NeverScrollableScrollPhysics()PageView构建器上使用选项,因此它不会受到滑动手势的影响。
  • 在表单步骤的每个按钮上(最后一步除外),我调用了_nextFormStep() 移动到下一个表单的方法。
  • WillPopScope()列表中每个的子项只是您想要滑动的表单/小部件。