在 Flutter 的 Nested Navigator 结构中,如何获取特定的 Navigator?

In a Nested Navigator Structure of Flutter, How do you get the a Specific Navigator?

我在嵌套 Navigator 时遇到了这个问题。所以像,

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: "/",
      routes: {
        '/': (context) => SomeOneView(),
        '/two': (context) => SomeTwoView(),
        '/three': (context) => SomeThreeView(),
      },
    );
  }
}

class SomeOneView extends StatefulWidget {
  @override
  _SomeOneViewState createState() => _SomeOneViewState();
}

class _SomeOneViewState extends State<SomeOneView> {
  @override
  Widget build(BuildContext context) {
   return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.indigo,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          MaterialButton(
            color: Colors.white,
            child: Text('Next'),
            onPressed: () => Navigator.of(context).pushNamed('/two'),
          ),
        ],
      ),
    );
  }
}



class SomeTwoView extends StatefulWidget {

  @override
  _SomeTwoViewState createState() => _SomeTwoViewState();
}

class _SomeTwoViewState extends State<SomeTwoView> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // Some implementation
      },
      child: Navigator(
        initialRoute: "two/home",
        onGenerateRoute: (RouteSettings settings) {
          WidgetBuilder builder;
          switch (settings.name) {
            case "two/home":
              builder = (BuildContext context) => HomeOfTwo();
              break;
            case "two/nextpage":
              builder = (BuildContext context) => PageTwoOfTwo();
              break;
          }
          return MaterialPageRoute(builder: builder, settings: settings);
        },
      ),
    );
  }
}

class HomeOfTwo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          MaterialButton(
            color: Colors.white,
            child: Text('Next'),
            onPressed: () => Navigator.of(context).pushNamed('two/nextpage'),
          ),
        ],
      ),
    );
  }
}

class PageTwoOfTwo extends StatelessWidget {

   @override
   Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.teal,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          MaterialButton(
            child: Text('Next'),
            onPressed: () => Navigator.of(context).pushNamed('/three'),
          ),
        ],
      ),
    );
  }
}

如您所见,我从 MaterialApp 提供的最顶层 Navigator 导航到 child Navigator'two/nextpage'然后应该转到 MaterialApp '/three'。问题是做 onPressed: () => Navigator.of(context).pushNamed('/three'), returns 当前 contextNavigator 即 child Navigator。我需要访问 MaterialAppNavigator 才能正确导航。这样做的正确方法是什么?

还有如何处理我要访问的 Navigator 位于 Navigator 堆栈中间某处的情况?

实际上,当您有子导航流程或内部旅程时,您必须使用嵌套 Navigator。请阅读 nesting navigators.

的文档

然而,要访问根导航器,您可以递归地从当前 Navigator 和 return 当前 Navigator 中查找父 Navigator 当它没有父 Navigator.

示例:

NavigatorState getRootNavigator(BuildContext context) {
  final NavigatorState state = Navigator.of(context);
  try {
    return getRootNavigator(state.context);
  } catch (e) {
    return state;
  }
}

//use it from any widget like
getRootNavigator(context);

编辑:

解决方法一:

为了得到一个特定的父 Navigator,我可以考虑扩展当前的 Navigator class 来接受一个 id 并通过 id。类似于:

class NavigatorWithId extends Navigator {
  const NavigatorWithId(
      {Key key,
      @required this.id,
      String initialRoute,
      @required RouteFactory onGenerateRoute,
      RouteFactory onUnknownRoute,
      List<NavigatorObserver> observers = const <NavigatorObserver>[]})
      : assert(onGenerateRoute != null),
        assert(id != null),
        super(
          key: key,
          initialRoute: initialRoute,
          onGenerateRoute: onGenerateRoute,
          onUnknownRoute: onUnknownRoute,
          observers: observers,
        );

  // when id is null, the `of` function returns top most navigator
  final int id;

  static NavigatorState of(BuildContext context, {int id, ValueKey<String> key}) {
    final NavigatorState state = Navigator.of(
      context,
      rootNavigator: id == null,
    );
    if (state.widget is NavigatorWithId) {
      // ignore: avoid_as
      if ((state.widget as NavigatorWithId).id == id) {
        return state;
      } else {
        return of(state.context, id: id);
      }
    }

    return state;
  }
}

在需要时使用 NavigatorWithId 而不是 Navigator,例如

return NavigatorWithId(
  id: 1,
  initialRoute: '/',
  onGenerateRoute: (_) =>
      MaterialPageRoute<dynamic>(builder: (_) => const YourPage()),
)

然后像这样访问它:

NavigatorWithId.of(context, id: 1)

方案二:

ValueKey 传递给导航器并制作一个 util 函数来匹配键和 return 所需的 Navigator.

类似

的函数
NavigatorState getNavigator(BuildContext context, {bool rootNavigator = false, ValueKey<String> key}) {
  assert(rootNavigator != null);
  final NavigatorState state = Navigator.of(
    context,
    rootNavigator: rootNavigator,
  );
  if (rootNavigator) {
    return state;
  } else if (state.widget.key == key) {
    return state;
  }
  try {
    return getNavigator(state.context, key: key);
  } catch (e) {
    return state;
  }
}

使用

return Navigator(
  key: const ValueKey<String>('Navigator1'),
  initialRoute: '/',
  onGenerateRoute: (_) =>
      MaterialPageRoute<void>(builder: (_) => const RootPage()),
);

并像

一样访问它
getNavigator(context, key: const ValueKey<String>('Navigator1'))

我可以看到这种方法的缺点,因为并非所有类型的键都受支持。

注意:我不认为上述任何解决方案是最好的或最优的。这些是我想出的几种方法。如果有人能想出更好的方法,我很想学习:)

希望对您有所帮助!

大多数时候,您只有 2 个 Navigator。

也就是获取嵌套的,做:

Navigator.of(context)

要获得根,请执行以下操作:

Navigator.of(context, rootNavigator: true)

对于更复杂的架构,到目前为止最简单的方法是使用 GlobalKey(因为在 build 期间您永远不会阅读 Navigators)

final GlobalKey<NavigatorState> key =GlobalKey();
final GlobalKey<NavigatorState> key2 =GlobalKey();

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: key,
      home: Navigator(
        key: key2,
      ),
    );
  }
}

你可以这样使用:

key.currentState.pushNamed('foo')

我在创建可以一次性全部关闭的流程时经常使用嵌套导航器。它需要父导航器(上一层)来弹出整个流程。为每个嵌套导航器创建一个全局密钥并将其存储在状态管理中对我来说似乎太多了。这是我的解决方案

class NestedNavigator {
  /// @param level 0 for current navigator. Same as Navigator.of()
  ///              1 for parent
  ///              >= 2 for grand parent
  static NavigatorState? of(BuildContext context, {int level = 1}) {
    var state = context.findAncestorStateOfType<NavigatorState>();
    while (state != null && level-- > 0) {
      state = state.context.findAncestorStateOfType<NavigatorState>();
    }
    return state;
  }
}

用法:

NestedNavigator.of(context).pop();

当然,如果你想要一个特定的导航器,你肯定应该存储 GlobalKey 并直接使用它。

你可以这样做,它总能在导航器和弹出窗口上方找到

 context.findAncestorStateOfType<NavigatorState>()?.context.findAncestorStateOfType<NavigatorState>()?.pop();