【问题标题】:How can I parse url parameter when using flutter navigator 2.0?使用flutter navigator 2.0时如何解析url参数?
【发布时间】:2021-07-31 01:50:30
【问题描述】:

我正在基于此文档构建颤振路由器:https://techblog.geekyants.com/navigation-20-routing-on-flutter-web

我的问题是如何在初始加载时获取 url 参数?例如我有指向RouterDelegate 中定义的路径/user 的url http://localhost:8080?id=1234/#/user。我可以打开 /user 的相关屏幕,但我应该在哪里解析 url 参数 id

【问题讨论】:

    标签: flutter flutter-web


    【解决方案1】:

    您可以使用 dart:core 中的 Uri 类

    https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri

    即:如果url = http://localhost:8082/game.html?id=15&randomNumber=3.14

    main() {
      print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
      print(Uri.base.query);  // id=15&randomNumber=3.14
      print(Uri.base.queryParameters['randomNumber']); // 3.14
    }
    

    【讨论】:

      【解决方案2】:

      无论您在浏览器中输入什么 URL,它都会被解析为 RouteInformationParser。在RouteInformationParser 中有一个方法parseRouteInformation(), 在该方法中,您将获得RouteInformation,您可以将RouteInformation 解析为

      final uri = Uri.parse(routeInformation.location);

      然后你可以在这里检查“id”。 例如 -> 假设这是您输入的路线
      http://localhost:8080?id=1234/#/user/2

       final id = uri.pathSegments.elementAt(1).toString();
      

      这将给出 id = 2;

      作为参考,您可以查看里面的parseRouteInformation方法代码 HomeRouteInformationParser (RouteInformationParser)你提到的文章中的类。

      【讨论】:

      • 我尝试了这个urlhttp://localhost:8080?id=1234/#/user/2的方法,但是在浏览器中输入后,它变成了http://localhost:8080/#/user/2,并且id参数被删除了。
      • 我认为这不是正确的 URL 格式。 Pramas 应该在路径资源之后。你可以试试这个localhost:8080/#/user/?id=1234。然后您可以将“id”参数设置为final uri = Uri.parse(routeInformation.location);id = uri.queryParameters["id"];(如此处的答案之一所述)
      • 或者你可以保持这种状态,只需将“#”localhost:52161/#/?id=12345/user 移动到这里,然后执行id = uri.queryParameters["id"];,你会得到id = "12345/user",你可以从中获取id -> uri.queryParameters["id"].split("/")[0]
      猜你喜欢
      • 2021-03-16
      • 2021-05-22
      • 2021-02-22
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2019-07-23
      相关资源
      最近更新 更多