Skip to content

[go_router] Come up with a better way to get the current location without context #129833

Closed
flutter/packages
#7651

Description

@ghaith-abtah-5

Is there an existing issue for this?

Use case

After the last update go_router 9.0.0, you have removed the location parameter from GoRouter and cannot be accessed any more without a context.

final GoRouter router = GoRouter(
     routes: [
          GoRoute(
                path: Routes.splashRoute,
                builder: (BuildContext context, GoRouterState state) {
                initSplashModule();
                return const SplashScreen();
                 },
               routes: [...],
               ],
            ),
           // other routes
        ],
     );

I cannot anymore use router.location to determine where am I in the application and there are certain scenarios where I cannot provide a context to GoRouterState.of(context).location, deep link or firebase messages that will pop or push some other routes from or to the navigation stack depending on the current location and state.
It was the easiest way to get the location and I can implement a way to do this on my own but it will take so much time and effort to get to the go_router package level.

Proposal

What was the reason to remove the location parameter and is there any chance that it will be back without a context in future versions?

Activity

  1. added
    in triagePresently being triaged by the triage team
    on Jul 3, 2023
  2. huycozy commented on Jul 3, 2023

    @huycozy
    Member

    Hi @ghaith-abtah-5
    As mentioned in Migration guide, you can work around this by following code (it is not guaranteed to work in later versions, though)

    GoRouter _router;
    final String location = _router.routerDelegate.currentConfiguration.uri.toString();
    final bool canPop = _router.routerDelegate.canPop;

    Please let us know your opinion if it applies to your case or not.

  3. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jul 3, 2023
  4. ghaith-abtah-5 commented on Jul 9, 2023

    @ghaith-abtah-5
    Author

    Thanks for reply.
    I cannot relay on this method because of "it is not guaranteed to work in later versions", and there was no warning or deprecation annotation that you are going to remove the location property.
    As I said, I can try to save the current route and implement this on my own but it will take time and effort.
    What is the reason that it was removed without any warning?

  5. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jul 9, 2023
  6. huycozy commented on Jul 10, 2023

    @huycozy
    Member

    Hi @ghaith-abtah-5,
    The Migration guide has been updated after 9.0.2, you can try below sample migration code:

    final RouteMatch lastMatch = _router.routerDelegate.currentConfiguration.last;
    final RouteMatchList matchList = lastMatch is ImperativeRouteMatch ? lastMatch.matches : _router.routerDelegate.currentConfiguration;
    final String location = matchList.uri.toString();

    there was no warning or deprecation annotation that you are going to remove the location property.

    Even though this is announced in the Changelog (this is a breaking change since 9.0.0), it should be warned in the API documentation. Thanks!

  7. added
    d: api docsIssues with https://api.flutter.dev/
    packageflutter/packages repository. See also p: labels.
    c: proposalA detailed proposal for a change to Flutter
    and removed
    in triagePresently being triaged by the triage team
    on Jul 10, 2023
  8. ghaith-abtah-5 commented on Jul 10, 2023

    @ghaith-abtah-5
    Author

    Thanks @huycozy for the clarification.
    I still didn't get the reason why you have made this change where a lot of developers use the location propriety the old way but maybe they didn't notice the change yet and now we can get it in three lines of code instead of one simple line.

  9. chunhtai commented on Jul 13, 2023

    @chunhtai
    Contributor

    The reason we remove the location is to avoid people looking up GoRouter.of(context).location since it will not rebuild the widget if it changes.

    but i agree the current workaround is ugly

  10. changed the title [-][go_router] Getting the current location without context[/-] [+][go_router] Come up with a better way to get the current location without context[/+] on Jul 13, 2023
  11. 16 remaining items

  12. flutter-triage-bot commented on May 25, 2024

    @flutter-triage-bot

    This issue was assigned to @chunhtai but has had no status updates in a long time. To remove any ambiguity about whether the issue is being worked on, the assignee was removed.

  13. removed
    ⏳Bot is counting down the days until it unassigns the issue
    on May 25, 2024
  14. Tanmay-R-Choudhary commented on Jul 11, 2024

    @Tanmay-R-Choudhary

    is it me or when I use this new way to get current location, it shows instead the previous location and not the current one ?... Is anyone having the same issue ?

    For me, it is rebuilding all the routes that were previously injected in the stack (im using context.push to navigate). This might just be me though, as all the pages in my project have the same path: /:param1/:param2

    I fetch additional data, via api call, based on the params and show content according to the response on the page. If I use context.go, everything works fine.

    The reason I need to use context.push is to support back button presses on mobile. I found a related issue, that was seemingly, resolved in previous versions. I dont know if its the same bug. I solved the issue by adding the following code (which I found in a comment on the previous issue I mentioned):

    Minimum code:

    extension GoRouterLocation on GoRouter {
      String get location {
        final RouteMatch lastMatch = routerDelegate.currentConfiguration.last;
        final RouteMatchList matchList = lastMatch is ImperativeRouteMatch
            ? lastMatch.matches
            : routerDelegate.currentConfiguration;
        return matchList.uri.toString();
      }
    }
    
    // in the route list ->
    GoRoute(
          path: '/:num',
          builder: (context, state) {
            if (state.matchedLocation != GoRouter.of(context).location) {
              return const SizedBox.shrink();
            }
    
            context.read<AppBloc>().add(Reload(url: state.pathParameters['num']!)); // api call
    
            return const Renderer();
          },
        )
    

    Here is the link to the comment: #123570 (comment)

  15. self-assigned this
    on Aug 1, 2024
  16. kevlar700 commented on Sep 13, 2024

    @kevlar700

    I was happy with Vrouter but it's dependencies not being updated in two years just broke my app.

    Vrouters ability to get the current url was nicer tbh

    selected: (context.vRouter.url == "my_url"),
    
  17. iapicca commented on Sep 13, 2024

    @iapicca

    I was happy with Vrouter but it's dependencies not being updated in two years just broke my app.

    Vrouters ability to get the current url was nicer tbh

    selected: (context.vRouter.url == "my_url"),
    

    I thought the point was NOT to use context

  18. mErrenst commented on Oct 22, 2024

    @mErrenst

    Not a GoRouter feature but a workaround I discovered:

    window.location isn't updated every time so that mostly shows the last element for me but window.history does get updated on every route.

    import 'package:universal_html/html.dart' as html;
    
    final location = html.window.history.state?['state']?['location'];
    

    You will of course need to do a null check with that. ;)
    Also that might throw exceptions when building for non-web so make sure to use error handling or good type casts/checks :)

  19. added
    r: fixedIssue is closed as already fixed in a newer version
    on Nov 5, 2024
  20. github-actions commented on Nov 19, 2024

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  21. locked as resolved and limited conversation to collaborators on Nov 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2Important issues not at the top of the work listc: proposalA detailed proposal for a change to Flutterd: api docsIssues with https://api.flutter.dev/p: go_routerThe go_router packagepackageflutter/packages repository. See also p: labels.r: fixedIssue is closed as already fixed in a newer version

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions