在 Flutter 中使用嵌套 Navigator 和 WillPopScope

问题描述 投票:0回答:1

在我的应用程序中,我想要一个自定义导航(仅更改屏幕的一部分并保留我在其中执行的操作的历史记录)。 为此,我使用了导航器,它可以很好地进行简单的导航。 但是,我想处理Android的后退按钮。 Flutter 中显然存在一个问题,这迫使我处理 Navigator 的父小部件中的后退按钮: https://github.com/flutter/flutter/issues/14083

因此,我需要在子级中检索 Navigator 的实例并对其调用 pop() 。我正在尝试为此使用 GlobalKey。

我现在正在尝试让它工作一段时间,并制作了一个示例项目只是为了测试它。 这是我的代码:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(title: 'Navigation Basics', home: MainWidget()));
}

class MainWidget extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: WillPopScope(
            onWillPop: () => navigatorKey.currentState.maybePop(),
            child: Scaffold(
                body: Padding(
              child: Column(
                children: <Widget>[
                  Text("Toto"),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Expanded(
                          child: RaisedButton(
                        child: Text('First'),
                        onPressed: () {
                          navigatorKey.currentState.pushNamed('/first');
                          // Navigator.push(
                          //   context,
                          //   MaterialPageRoute(builder: (context) => SecondRoute()),
                          // );
                        },
                      )),
                      Expanded(
                          child: RaisedButton(
                        child: Text('Second'),
                        onPressed: () {
                          navigatorKey.currentState.pushNamed('/second');
                        },
                      ))
                    ],
                  ),
                  Expanded(
                      child: Stack(
                    children: <Widget>[
                      Container(
                        decoration: BoxDecoration(color: Colors.red),
                      ),
                      ConstrainedBox(
                          constraints: BoxConstraints.expand(),
                          child: _getNavigator()),
                    ],
                  )),
                ],
              ),
              padding: EdgeInsets.only(bottom: 50),
            ))));
  }

  Navigator _getNavigator() {
    return Navigator(
        key: navigatorKey,
        initialRoute: '/',
        onGenerateRoute: (RouteSettings settings) {
          WidgetBuilder builder;
          switch (settings.name) {
            case '/':
              builder = (BuildContext _) => FirstRoute();
              break;
            case '/second':
              builder = (BuildContext _) => SecondRoute();
              break;
            default:
              throw new Exception('Invalid route: ${settings.name}');
          }
          return new MaterialPageRoute(builder: builder, settings: settings);
        });
  }
}

class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("GO TO FRAGMENT TWO"),
            onPressed: () => Navigator.of(context).pushNamed("/second"),
          )
        ],
      ),
      decoration: BoxDecoration(color: Colors.green),
    );
  }
}

class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("GO TO FRAGMENT ONE"),
            onPressed: () => Navigator.of(context).pop(),
          )
        ],
      ),
      decoration: BoxDecoration(color: Colors.blue),
    );
  }
}

但这并没有像我想要的那样工作。默认的导航器似乎仍在使用:打开 SecondRoute 并按 Android 返回按钮后,它只是离开应用程序,而不是返回到第一条路线。

我怎样才能实现我想要的?

flutter routes back flutter-navigation
1个回答
17
投票

遵循 onWillPop 的文档:

  /// Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
  ///
  /// If the callback returns a Future that resolves to false, the enclosing
  /// route will not be popped.
  final WillPopCallback onWillPop;

您的处理程序应指示不应关闭封闭路由,因此返回 false 将解决您的问题。

将您的处理程序更改为此有效:

    onWillPop: () async {
      navigatorKey.currentState?.maybePop();
      return false;
    },
© www.soinside.com 2019 - 2024. All rights reserved.