Home > Software design >  Screen keeps rendering after initializing Firebase
Screen keeps rendering after initializing Firebase

Time:02-01

So I'm trying to implement authentication using Firebase and I got an error saying

[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

I found a way to deal with the error by adding the following code to my main.dart file:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(StockApp());
}

The method to check if the user is logged in is as follows:

isLoggedIn() async {
    _auth.authStateChanges().listen((user) {
      if (user != null)
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => Home()));
      else
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => Login()));
    });
  }

@override
  void initState() {
    super.initState();
    this.isLoggedIn();
  }

The error is gone but now my login page keeps rendering endlessly. enter image description here

CodePudding user response:

Here you are navigating to the screen on listening the stream so it will continuously pushing the widget to the stack.Instead of this you can use

User? _user;
isLoggedIn() async {
    _auth.authStateChanges().listen((user) {
      _user=user;
      setState((){})
      
    });

    if (user != null)
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => Home()));
      else
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => Login()));
  }

CodePudding user response:

Wrap this.isLoggedIn method inside addPostFrameCallback as

WidgetsBinding.instance.addPostFrameCallback((_){
     this.isLoggedIn()
});
  •  Tags:  
  • Related