runMiddleware method
Implementation
Future<RouteDecoder?> runMiddleware(RouteDecoder config) async {
// 获取 [GetPage] 中的 [middlewares] 列表
final middlewares = config.currentTreeBranch.last.middlewares;
if (middlewares.isEmpty) {
// 如果没有中间件, 则不重定向, 直接返回传入的 [RouteDecoder], 即将要显示界面
return config;
}
var iterator = config;
// 正序遍历中间件, 所有 [GetPage] 里前面的中间件会先执行
for (var item in middlewares) {
// 执行 redirectDelegate 函数
var redirectRes = await item.redirectDelegate(iterator);
// 返回 null 和上面返回 config 结果是一样的, 都是不重定向
if (redirectRes == null) {
config.route?.completer?.complete();
return null;
}
// 如果 redirectRes 不为空则覆盖 iterator
if (config != redirectRes) {
config.route?.completer?.complete();
Get.log('Redirect to ${redirectRes.pageSettings?.name}');
}
iterator = redirectRes;
// Stop the iteration over the middleware if we changed page
// and that redirectRes is not the same as the current config.
// 如果 redirectDelegate 中返回的不是传入的 config, 则结束迭代
// 当其中某一个中间件进行了重定向, 则后面所有的中间件都不会再执行
if (config != redirectRes) {
break;
}
}
// If the target is not the same as the source, we need
// to run the middlewares for the new route.
// 如果进行了重定向,则会递归调用 runMiddleware,运行重定向后新路由的所有中间件。
if (iterator != config) {
return await runMiddleware(iterator);
}
// 返回重定向后最终的 [RouteDecoder]
return iterator;
}