Flutter navigate to screen without delay

Viewed 933

I have a login screen, in my form button, i do the check and then call Shared Preferences to set the login flag, and initState i call a method to check the value and redirect to homeScreen. Now all went well, but i am able to see the login form for a second or so, then i get redirected to home. I wish to not see the login form at all. How can i do that? Here is the content of initState method:

_loadLoginStatus() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _loginStatus =prefs.getBool('loginStatus') ?? false;
      if(_loginStatus == true){
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => HomeScreen()));
      }
    });
  }
1 Answers

Don't setup your login screen as a home screen on your AppWidget.

Instead of this create a LoadingScreen or SplashScreen and check login status here.

class LoadingScreen extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<LoadingScreen> {

  @override
  Widget build(BuildContext context) {
    _checkLogin(context);
    return Scaffold(body: Center(child: CircularProgressIndicator()));
  }

  _checkLogin(BuildContext context) async {
    // do what you want with await functions
    if (condition) {
      Navigator.push(
            context, MaterialPageRoute(builder: (context) => HomeScreen()));
    } else {
      Navigator.push(
            context, MaterialPageRoute(builder: (context) => LoginScreen()));
    }
  }
}
Related