Multiple redirect notifiers in go_router using composition pattern.

Agboola yusuf
2 min readApr 2, 2022

--

Photo by Aaron Burden on Unsplash

go_router is arguably one of the best solutions that makes flutter navigator 2.0 easier to implement. It is easy to get started and has really great documentation.

However, like most new flutter packages, go_router still has a long way to go to become complete, which means some fairly complex use cases may not be easy to achieve.

One of those use cases is the need to have multiple redirect notifiers for go_router. The go_router constructor allows you to pass in a notifier instance which it listens to for changes before then running the application’s redirect logic.

The redirect logic can be used for a variety of use cases, for example, to check if a user is authenticated when visiting a protected route and then allow the user to pass or redirect to onboarding if not authenticated. Let’s call this AuthenticationNotifier.

class AuthenticationNotifier extends ChangeNotifier {
//...some authentication logic
}

Another scenario is to listen to new deep-links coming into the app and redirect to a route based on the deep-link that was received. Let’s call this DeeplinkNotifier.

class DeeplinkNotifier extends ChangeNotifier {
//...some deeplink logic
}

The issue now is we have two notifiers we want go_router to listen to but go_router constructor allows us to pass in just one. Of course, it’s possible to combine the logic for both Deeplinknotifier and authenticationNotifier and have a single class but this gets messy really fast, especially as there may be a need to add more notifier logic in the future.

Composition pattern to the rescue.
In object-oriented programming, a composition pattern is a design pattern that allows composing multiple objects into a tree-like structure and working with the structure as if it were a singular object.

Following the composition pattern, we can create a base redirect notifier and add other notifier objects to it as fields. The base notifier is then passed to the go_router constructor.

class RedirectNotifiers extends ChangeNotifier {
RedirectNotifiers(){
deeplinkNotifier = DeepLinkNotifier(this);
authenticationNotifier = AuthenticationNotifier(this);
}

late final deeplinkNotifier
late final authenticationNotifier;
}

This way, we pass a single notifier(RedirectNotifiers) instance to the go_router constructor as required, but we have multiple notifier logics that the go_router listens for.

It’s useful to note that some modifications were made to pass in RedirectNotifiers instance to the other members so they can use the instance in their respective logic as needed.

What do you think about this workaround for the go_router notifier? Any suggestions or improvements?

--

--