Search code examples
androidflutterfirebaseauthenticationmobile

Waiting for a delay in splash screen before redirecting to home if u are logged in flutter


I am developing a flutter app , I configured it with firebase , I also do have a splash screen . The problem that i am facing is related to redirection to home screen if the user is already logged in.This is the initial code , before adding the StreamBuilder i was using named routes but here i had to switch it to return. I tried many approaches like using a Future.deplayed in the initstate() or another approach in the 2nd snippet of code.

import 'package:carecraft/ui/screens/login.dart';
import 'package:carecraft/ui/theme.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/adapters.dart';

import 'home.dart';

class Splash extends StatefulWidget {
  const Splash({super.key});

  @override
  State<Splash> createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  @override
  void initState(){
    // TODO: implement initState
    super.initState();
    init();
  }
  void
  init() async {
    await Hive.initFlutter();
    Hive.registerAdapter<TimeOfDay>(TimeOfDayAdapter());
    Box _box =await Hive.openBox<TimeOfDay>('drug');
  }
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        body: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [bleuTresTresClair,
                    bleuTresClair,
                    bleuClair,
                    bleu,
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight

              )
          ),
          child:  Center(
            child:Stack(
                alignment: Alignment.center, // Align items at the top center
                children: [
                  Positioned(
                    //to has 20% of the screen height
                      top:   0,
                      child: Image.asset(
                        'assets/carecraft.png',
                        height:MediaQuery.of(context).size.width * 0.9,
                        width: MediaQuery.of(context).size.height * 0.9,
                      )
                  ),
                  Positioned(
                    top: MediaQuery.of(context).size.height * 0.41,
                    left: MediaQuery.of(context).size.width * 0.45,// Adjust the top position as needed
                    child: Image.asset(
                      'assets/androidinsat.png',
                      height:MediaQuery.of(context).size.width * 0.23,
                      width: MediaQuery.of(context).size.height * 0.23,
                    ),),
                  Positioned(
                    top: MediaQuery.of(context).size.height * 0.45, // Adjust the top position as needed
                    child: Image.asset(
                      'assets/splash.png',
                      height:MediaQuery.of(context).size.width * 1.1,
                      width: MediaQuery.of(context).size.height * 1.1,
                    ),
                  ),
                  StreamBuilder<User?>(
                      stream: FirebaseAuth.instance.authStateChanges(),
                      builder: (BuildContext context, AsyncSnapshot<User?> snapshot) {
                        if (snapshot.connectionState == ConnectionState.active ) {
                          if (snapshot.hasData && snapshot.data != null) {
                            return Home();
                          }
                          else{
                            return LogIn();
                          }
                        }
                        else{
                          return CircularProgressIndicator();
                        }
                      }

                  )
                ]
            ),
          ),
        )
    );
  }
}

2nd Snippet of code:

import 'package:carecraft/ui/screens/login.dart';
import 'package:carecraft/ui/theme.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/adapters.dart';

import 'home.dart';

class Splash extends StatefulWidget {
  const Splash({super.key});

  @override
  State<Splash> createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  bool delayCompleted = false;
  @override
  void initState(){
    // TODO: implement initState
    super.initState();
    init();
  }
  void
  init() async {
    await Hive.initFlutter();
    Hive.registerAdapter<TimeOfDay>(TimeOfDayAdapter());
    Box _box =await Hive.openBox<TimeOfDay>('drug');
  }
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        body: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [bleuTresTresClair,
                    bleuTresClair,
                    bleuClair,
                    bleu,
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight

              )
          ),
          child:  Center(
            child:Stack(
                alignment: Alignment.center, // Align items at the top center
                children: [
                  Positioned(
                    //to has 20% of the screen height
                      top:   0,
                      child: Image.asset(
                        'assets/carecraft.png',
                        height:MediaQuery.of(context).size.width * 0.9,
                        width: MediaQuery.of(context).size.height * 0.9,
                      )
                  ),
                  Positioned(
                    top: MediaQuery.of(context).size.height * 0.41,
                    left: MediaQuery.of(context).size.width * 0.45,// Adjust the top position as needed
                    child: Image.asset(
                      'assets/androidinsat.png',
                      height:MediaQuery.of(context).size.width * 0.23,
                      width: MediaQuery.of(context).size.height * 0.23,
                    ),),
                  Positioned(
                    top: MediaQuery.of(context).size.height * 0.45, // Adjust the top position as needed
                    child: Image.asset(
                      'assets/splash.png',
                      height:MediaQuery.of(context).size.width * 1.1,
                      width: MediaQuery.of(context).size.height * 1.1,
                    ),
                  ),
                  StreamBuilder<User?>(
                      stream: FirebaseAuth.instance.authStateChanges(),
                      builder: (BuildContext context, AsyncSnapshot<User?> snapshot) {
                        Future.delayed(Duration(seconds: 3, milliseconds: 500), () {
                          delayCompleted = true;
                        });
                        if (snapshot.connectionState == ConnectionState.active && delayCompleted) {
                          if (snapshot.hasData && snapshot.data != null) {
                            return Home();
                          }
                          else{
                            return LogIn();
                          }
                        }
                        else{
                          return CircularProgressIndicator();
                        }
                      }

                  )
                ]
            ),
          ),
        )
    );
  }
}


Solution

  • Do something like this in your initState()

    @override
      void initState() {
        super.initState();
    
        doLogin().then((isLoggedIn) {
          if (isLoggedIn) {
            debugPrint("The user was logged in.  Going to home page");
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => const MyHomePage()),
            );
          } else {
            debugPrint("The user was NOT logged in. Staying on login page");
          }
        });
      }
    

    When you get the result from Firebase, you can use Navigator.pushReplacement() to go to the next page (or do whatever you need to do).