Go_router current route queryParams
Asked Answered
T

2

5

Using go_router :

GoRouter.of(context).location

gives us the current route path such as /product/10110 but I'd like to know how to also get the current route queryParams in a similar fashion

(outside of the GoRoute builder)

Travesty answered 30/12, 2022 at 10:27 Comment(0)
G
6

You can now have this functionality.

class SampleWidget extends StatelessWidget {
  SampleWidget({super.key});

  @override
  Widget build(BuildContext context) {
    Map<String,dynamic> qparams = GoRouterState.of(context).uri.queryParams;

    return const Scaffold(
      body: ...
    );
  }
}

This way you can directly access the query params you send using go_router, like:

context.goNamed("page", queryParams: {"name": "Addy", "age": "22"}),
Globulin answered 18/2, 2023 at 9:58 Comment(0)
H
2

go_router has it's qweryParams in its state.

Hence pass the state to the page


Router

 GoRoute(
    name: "test",
    path: "/test",
    builder: (context, state) {
      return SampleWidget(
        goRouterState: state,  πŸ‘ˆ Pass state here
      );
    },
  ),

Usage

context.goNamed("test", queryParams: {"email": "[email protected]", "age": "25"}),

Accesing in the page

class SampleWidget extends StatelessWidget {
  GoRouterState? goRouterState;
  SampleWidget({super.key, this.goRouterState});

  @override
  Widget build(BuildContext context) {
    print(goRouterState?.queryParams.toString()); πŸ‘ˆ access anywhere like so

    return const Scaffold(
      body: ...
    );
  }
}
Homophonic answered 3/1, 2023 at 8:9 Comment(2)
Right, I guess I was more wondering if I could more easily access it through GoRouter.of(context) but I'm guessing not ! Thanks for your answer I will up vote it :) – Travesty
Currently it's not possible using GoRouter.of(context) , so this is the work around – Homophonic

© 2022 - 2024 β€” McMap. All rights reserved.