【问题标题】:Can't find description of MaterialApp routes parameters找不到 MaterialApp 路由参数的描述
【发布时间】:2021-09-30 04:20:48
【问题描述】:

目前我正在学习飞镖和颤振。在阅读 Flutter 食谱时,我发现了这样的结构 (source):

'/': (context) => FirstScreen()

在打了这个基础之后,我试图在 dart 文档中找到可以解释的东西,但没有找到有用的东西。

我什至不知道这东西是怎么叫的。


请告诉我这条线在做什么(除了它在粗箭头之后重定向到 Widget)或者,它在调用什么,继续研究。

谢谢。

【问题讨论】:

    标签: flutter dart navigation


    【解决方案1】:

    TLDR:它是一个Map<String, Widget Function(BuildContext)>,当你调用Navigator.pushNamed时,会在这个map中查找名称,并调用相应的函数来构建小部件。

    更长的答案

    您可能会发现使用 IDE 的“go-to definition”功能(在大多数 IDE 中是 ctrl/cmd + click)很有帮助,该功能会将您带到源代码中定义特定事物的位置。

    首先,这是在一个叫做“地图文字”的东西里面。地图文字看起来有点像这样:

    final map = {
      'hello': 'world'
    };
    

    这相当于写:

    final map = Map();
    map['hello'] = 'world';
    

    这只是创建预填充Map 的简写。所以下面是Map<String, Widget Function(BuildContext)

    routes: {
      '/': (context) => MyWidget(),
      '/other': (context) => OtherWidget(),
    }
    

    这允许你通过它的'key'来查找一个值,你得到的值是一个Widget Function(BuildContext)

    BuildContext context = ...;  // get a context from somewhere
    Widget Function(BuildContext) function = routes['/'];  // look up the key '/'
    Widget widget = function(context);  // call the function with the context
    

    您正在描述MaterialApp() 构造函数的routes 参数。如果您 ctrl+单击单词 routes,它会将您带到以下定义:

      /// The application's top-level routing table.
      ///
      /// When a named route is pushed with [Navigator.pushNamed], the route name is
      /// looked up in this map. If the name is present, the associated
      /// [WidgetBuilder] is used to construct a [MaterialPageRoute] that performs
      /// an appropriate transition, including [Hero] animations, to the new route.
      ///
      /// {@macro flutter.widgets.widgetsApp.routes}
      final Map<String, WidgetBuilder>? routes
    

    本质上,这是一种告诉 Flutter 你每个名字是什么意思的方法。如果你打电话给Navigator.pushNamed(context, '/home'),但你没有这张地图,Flutter 不会知道/home 是为了将用户带到HomeWidget()(或其他任何名称)。此地图是提供名称和小部件之间链接的一种方式。

    【讨论】:

    • 非常感谢!我不能给 +1 代表,因为它说我“你需要至少 15 声望......”,我很抱歉 :(
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2018-09-04
    • 2022-07-01
    相关资源
    最近更新 更多