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()(或其他任何名称)。此地图是提供名称和小部件之间链接的一种方式。