1

My question is quite simple: How do i initiate navigation from the ChangeNotifier? I have a dashboard setup with a consumer and i want to change the route depending on the result of certain operations in the ChangeNotifier Model.

A similar question has been asked before but it has gone unanswered: How to Navigate from ChangeNotifier?

fideldonson
  • 581
  • 3
  • 15

2 Answers2

0

Well it might seem obvious to all but me. You just have to pass the context into the ChangeNotifier and then you can Navigator.pushNamed(context, routeName);

I was searching for a way to make that happen from the widget tree in place. it did not occur to me to just do it from the model - and i am still not sure it is best practice - but it works.

fideldonson
  • 581
  • 3
  • 15
-1
1. main.dart
 MaterialApp(
navigatorKey: NavigationService().navigatorKey,
)

2 create new class

class NavigationService {
 final GlobalKey<NavigatorState> navigatorKey =
  new GlobalKey<NavigatorState>();
 GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
Future<dynamic> navigateTo(String routeName) {
return navigatorKey.currentState.pushNamed(routeName);
}}
  1. in Model class use this in any function

    NavigationService>().navigateTo(homePageRoute)  // your router name
    
Johny Saini
  • 879
  • 1
  • 5
  • 6