Getx在路由之前检查命名路由是否存在



我正在使用深链接的Getx路由。我想添加一个保护,检查传入的deep plink路由是否有效。有没有一个函数我还没找到呢?

代码就像这样简单:

var str = 'my/deep/link'
if(doesNamedRouteExist(str)){
Get.toNamed(str);
}

有什么想法/建议/优雅的解决方案吗?谢谢!

解决方案

使用下面的函数检查路由树中是否存在路由

bool matchRoute(String routeName) {
for (var route in Get.routeTree.routes) {
if (route.name == Homepage.name) {
return true;
}
}
return false;
}

此函数使用Get.routeTree.routes获取路由树中的路由列表,然后检查路由列表以查找与routeName同名的路由

此解决方案适用于命名路由

Get有以下方法:

Get.routeTree.matchRoute(path)

我们这样使用它:

static bool isPathValid(String path) {
// If exactly matches root then it is fine.
if (path.removeAllWhitespace == '/') return true;
final List<GetPage<dynamic>> treeBranch =
Get.routeTree.matchRoute(path).treeBranch;
// Note: for some reason .where was not working on the .treeBranch iterable.
final List<String> list = <String>[];
for (final GetPage<dynamic> element in treeBranch) {
// Need to exclude '/' as it is the root route so any uri beginning
// with / will give a valid path
if (element.name != '/') {
list.add(element.name);
}
}
return list.isNotEmpty;
}

正如你在注释中看到的,匹配路由将遍历所有有效路由,如果根路由是'/',任何带有'/'的路径都可能给出有效路由的假阳性。你看,我们把它排除在外了。我建议你尝试一下。

我建议使用

static const id = "route name" 

作为screen/class的属性。

然后使用

中的const变量
Get.toNamed(MyAppScreenA.id)
  • 另一种方法是为路由名创建一个常量文件,并将id变量存储在那里。

最新更新