找不到 MaterialApp 路由参数的描述

Can't find description of MaterialApp routes parameters

目前我正在学习 dart 和 flutter。在阅读 flutter cookbook 时,我发现了这样的结构 (source):

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

在此基础之后,我试图在 dart 文档中找到解释该内容的内容,但没有找到有用的内容。

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


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

谢谢。

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

更长的答案

您可能会发现使用 IDE 的“转到定义”功能很有帮助(在大多数 IDE 中,这是 ctrl/cmd + 单击),这将需要你到源中定义特定事物的位置。

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

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

这相当于写作:

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

创建预填充Map只是一个shorthand。所以下面是一个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()(或其他名称)。此映射是在名称和小部件之间提供 link 的一种方式。