I'm using this way to authenticate the user and redirect to the pages but the first "void initState" appears as unusable and when the user is not logged in it ends up not redirecting to Welcome(); What can be wrong?

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  Future _loggedUserValidation() async {
    FirebaseAuth auth = FirebaseAuth.instance;

    FirebaseUser loggedUser = await auth.currentUser();
    if (loggedUser != null) {
      Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    } else {
      @override
      void initState() {
        super.initState();

        Future.delayed(Duration(seconds: 2)).then((value) =>
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => Welcome())));
      }
    }
  }

  @override
  void initState() {
    _loggedUserValidation();
    super.initState();
  }


Solution 1: quoci

Why do you create the method initState inside the else? You can just do it like in the if statement.

class _SplashPageState extends State<SplashPage> {
  Future<void> _loggedUserValidation() async {
    FirebaseAuth auth = FirebaseAuth.instance;

    FirebaseUser loggedUser = await auth.currentUser();
    if (loggedUser != null) {
      Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    } else {
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => Welcome()));
    }
  }

  @override
  void initState() {
    _loggedUserValidation();
    super.initState();
  }
}