Home Articles

应用程序加载时,默认路由('/')是否会添加到导航器堆栈

Asked
Viewed 915 times
0

举个例子:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyApp(),));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () => Navigator.pop(context),
          child: Text('Go Back'),
        ),
      ),
    );
  }
}

以上示例的屏幕截图:

enter image description here

我知道我可以使用 Navigator.canPop(context) 来阻止这种行为 .

我的简单问题是,当app启动一个页面时,默认路由 "/" 会添加到 Navigator 列表吗?

enter image description here

如果默认路由推送到 Navigator 堆栈(如上图所示),当按 Go Back (在上例中)时,它是否会从 Navigator 堆栈弹出?

1 Answer

  • 0

    阅读doc for Navigator class

    MaterialApp是最简单的设置方式 . MaterialApp的主页成为导航器堆栈底部的路径 . 这是您在推出应用时看到的内容 .

    阅读下面的app.dart file source code内联评论:

    /// The widget for the default route of the app ([Navigator.defaultRouteName],
      /// which is `/`).
      ///
      /// This is the route that is displayed first when the application is started
      /// normally, unless [initialRoute] is specified. It's also the route that's
      /// displayed if the [initialRoute] can't be displayed.
      ///
      /// To be able to directly call [Theme.of], [MediaQuery.of], etc, in the code
      /// that sets the [home] argument in the constructor, you can use a [Builder]
      /// widget to get a [BuildContext].
      ///
      /// If [home] is specified, then [routes] must not include an entry for `/`,
      /// as [home] takes its place.
      ///
      /// The [Navigator] is only built if routes are provided (either via [home],
      /// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
      /// [builder] must not be null.
      ///
      /// The difference between using [home] and using [builder] is that the [home]
      /// subtree is inserted into the application below a [Navigator] (and thus
      /// below an [Overlay], which [Navigator] uses). With [home], therefore,
      /// dialog boxes will work automatically, [Tooltip]s will work, the [routes]
      /// table will be used, and APIs such as [Navigator.push] and [Navigator.pop]
      /// will work as expected. In contrast, the widget returned from [builder] is
      /// inserted _above_ the [MaterialApp]'s [Navigator] (if any).
    final Widget home;
    

    是的,当将一个小部件添加到 home 属性时,这将添加到 Navigator 堆栈,这意味着在该页面中调用 pop 时,将从 Navigator 堆栈中删除/弹出默认路由 .

    注意:根据this issues in github,不要尝试 pop 初始路由/页面(默认路由) .

Related