Abion47
Abion47

Reputation: 24746

Class callback functions for when a widget is routed to/away from

I'm looking for a way to have some kind of callback function in my widget class. In essence, I'm looking for something like this:

class SomeWidget extends StatefulWidget with RouteHandlerMixin {
  // ...

  void onRouteTo(Route oldRoute) {
    // Do stuff before this widget gets routed to
    // Perhaps return a bool to approve/cancel the route
  }

  void onRouteAway(Route newRoute) {
    // Do stuff before this widget gets routed away from
    // Perhaps return a bool to approve/cancel the route
  }

  // ...
}

Does Flutter have any support for this kind of behavior? The closest I could find/think of is some janky solution involving putting the logic within the onGenerateRoute property of the root MaterialApp.

Upvotes: 2

Views: 1151

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277587

What you're looking for is RouteAware

// Register the RouteObserver as a navigation observer.
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
void main() {
  runApp(MaterialApp(
    home: Container(),
    navigatorObservers: [routeObserver],
  ));
}

class RouteAwareWidget extends StatefulWidget {
  State<RouteAwareWidget> createState() => RouteAwareWidgetState();
}

// Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context));
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    // Route was pushed onto navigator and is now topmost route.
  }

  @override
  void didPopNext() {
    // Covering route was popped off the navigator.
  }

  @override
  Widget build(BuildContext context) => Container();

}

Upvotes: 2

Related Questions