flutterflutter-go-router

Prevent already open route to open again with go_router


I use go_router in combination with flutter navigation api. Here are my routes:

From home I would call Navigator.push() to get to objects and the context.push() to get to object.

I have no child routes yet, I know. It is not the point here, I think. I get push notification which should navigate to object-route. It works fine, but if object-route is already open, it opens it again. So when I click on back I get back to object-route.

Should I check the path in redirect to prevent duplicate screen or I am using go_router wrong?

I am using context.push() upon notification is tapped.


Solution

  • Check if the current location is already /object before pushing

    final currentLocation = GoRouter.of(context).location;
    if (currentLocation != '/object') {
      context.push('/object');
    }
    

    This ensures you don't push the same screen twice if it's already open.