颤动:在页面上使用导航器时如何处理后退按钮按下

flutter: how to handle back button press when using navigator with pages

我正在尝试实施 Navigator 2.0 方法。我唯一无法正常工作的是按下后退按钮。当我按下后退按钮时,应用程序只是退出而不是转到上一页。我尝试了 WillPopPage 小部件,但后退按钮绕过了它。

这里是一个示例代码,它不适用于背压。

import 'package:flutter/material.dart';

main(List<String> args) {
  runApp(TestApp());
}

class TestApp extends StatefulWidget {
  @override
  _TestAppState createState() => _TestAppState();
}

class _TestAppState extends State<TestApp> {
  bool go = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Navigator(
        pages: [
          // page 1
          MaterialPage(
            child: W1(onTapped: () {
              setState(() => go = true);
            }),
          ),
          // page 2
          if (go) MaterialPage(child: W2()),
        ],
        onPopPage: (route, result) {
          if (!route.didPop(result)) return false;
          go = false;
          return true;
        },
      ),
    );
  }
}

class W1 extends StatelessWidget {
  final void Function() onTapped;

  const W1({Key key, this.onTapped}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          onPressed: onTapped,
          child: Text("Go to second"),
        ),
      ),
    );
  }
}

class W2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("pressing the back button is exiting the app.."),
      ),
    );
  }
}

我已经用这种方法写了很多代码,所以我不能再回到命令式导航了。如何用这种方法处理背压?

你必须使用 'WillPopScope' https://api.flutter.dev/flutter/widgets/WillPopScope-class.html

示例

Future<bool> _willPopScopeCall() async {
// code to show toast or modal
return true; // return true to exit app or return false to cancel exit
}

//wrap your scaffold with WillPopScope
WillPopScope(child: new Scaffold(), onWillPop: _willPopScopeCall);

如果不扩展 RouterDelegate,Navigator 2.0 是不可能做到这一点的。按下系统后退按钮由 RouteDelegatepopRoute 方法处理。根据文档:

The method should return a boolean Future to indicate whether this delegate handles the request. Returning false will cause the entire app to be popped.

默认实现总是returns false。因此,您必须覆盖它以处理系统后退按钮按下。

更新
我发表了一篇文章,介绍了使用 Navigator 2.0 的快速且易于理解的指南。你可以找到它 here.