Home > OS >  currentUser Flutter won't change state
currentUser Flutter won't change state

Time:09-06

I want two show a widget if the user is logged in and show a different one, if not.

This is what the snippet of the code looks like:

    class _AccountWidgetState extends State<AccountWidget> {
      bool loggedIn = false;
      final _auth = FirebaseAuth.instance;
      late User loggedInUser;
    
      @override
      void initState() {
        getCurrentUser();
        super.initState();
      }
    
      void getCurrentUser() {
        try {
          final user = _auth.currentUser;
          if (user != null) {
            loggedInUser = user;
            setState(() {
              loggedIn == true;
            });
          }
        } catch (e) {
          print(e);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: loggedIn
              ? const Text('logged in')
              : SizedBox(...     ),
    );
  }
}

No matter what the loggedIn boolean will be always false.

What's going on here?

CodePudding user response:

You are not making any assignment here. It is a condition.

 void getCurrentUser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        setState(() {
        //  Wrong ->  loggedIn == true; 
        loggedIn = true; 
        });
      }
    } catch (e) {
      print(e);
    }
  }
  • Related