flutterdartnavigation

Reload Flutter navigator state to the first screen


I would like to reload navigator state to the first screen based on the if condition of department change. My code is given below:

  void didChangeDependencies() {
    super.didChangeDependencies();

    AuthenticationNotifier authenticationNotifier =
        Provider.of<AuthenticationNotifier>(context, listen: true);
    UserAppDepartmentModel? currentDepartment =
        authenticationNotifier.getSelectedUserAppDepartment();

    // Check if the Department has changed
    if (currentDepartment != previousDepartment) {
      setState(() {
        cSelectedUserAppDepartment = currentDepartment;
        previousDepartment = currentDepartment; // Update previous value
      });
    }
  }```

please let me know how to do it. 

Solution

  • It can be solved using NavigatorKey. As follow:

     void didChangeDependencies() {
        super.didChangeDependencies();
    
        AuthenticationNotifier authenticationNotifier =
            Provider.of<AuthenticationNotifier>(context, listen: true);
        UserAppDepartmentModel? currentDepartment =
            authenticationNotifier.getSelectedUserAppDepartment();
    
        // Check if the Department has changed
        if (currentDepartment != previousDepartment) {
          setState(() {
            cSelectedUserAppDepartment = currentDepartment;
            previousDepartment = currentDepartment; // Update previous value
            resetNavigators();
          });
        }
      }
    
      void resetNavigators() {
        YourNavigatorKey.currentState?.popUntil((route) => route.isFirst);
       
      }