Flutter remove all routes

前端 未结 10 1863
难免孤独
难免孤独 2021-01-30 04:46

I want to develop a logout button that will send me to the log in route and remove all other routes from the Navigator. The documentation doesn\'t seem to explain h

10条回答
  •  既然无缘
    2021-01-30 05:29

    This is working for me. Actually, I was working with bloc but my issue was login screen bloc. It was not updating after logout. It was holding the previous model data. Even, I entered the wrong entry It was going to Home Screen.

    Step 1:

    Navigator.of(context).pushNamedAndRemoveUntil(
            UIData.initialRoute, (Route route) => false);
    

    where, UIData.initialRoute = "/" or "/login"

    Step 2:

    It's working to refresh the screen. If you are working with Bloc then It will very helpful.

    runApp(MyApp());
    

    where, MyApp() is the root class.

    Root class (i.e. MyApp) code

    class MyApp extends StatelessWidget {
    
      final materialApp = Provider(
          child: MaterialApp(
              title: UIData.appName,
              theme: ThemeData(accentColor: UIColor().getAppbarColor(),
                fontFamily: UIData.quickFont,
              ),
              debugShowCheckedModeBanner: false,
              //home: SplashScreen(),
              initialRoute: UIData.initialRoute,
              routes: {
                UIData.initialRoute: (context) => SplashScreen(),
                UIData.loginRoute: (context) => LoginScreen(),
                UIData.homeRoute: (context) => HomeScreen(),
              },
              onUnknownRoute: (RouteSettings rs) => new MaterialPageRoute(
                  builder: (context) => new NotFoundPage(
                    appTitle: UIData.coming_soon,
                    icon: FontAwesomeIcons.solidSmile,
                    title: UIData.coming_soon,
                    message: "Under Development",
                    iconColor: Colors.green,
                  )
              )));
    
      @override
      Widget build(BuildContext context) {
        return materialApp;
      }
    }
    
    void main() => runApp(MyApp());
    

    Here is My Logout method,

    void logout() async {
        SharedPreferences preferences = await SharedPreferences.getInstance();
        preferences.clear();
    
        // TODO: we can use UIData.loginRoute instead of UIData.initialRoute
        Navigator.of(context).pushNamedAndRemoveUntil(
            UIData.initialRoute, (Route route) => false);
        //TODO: It's working as refresh the screen
        runApp(MyApp());
      }
    

提交回复
热议问题