Home > Back-end >  Flutter Firebase UI not updating and showing correct user info after signing out and in with differe
Flutter Firebase UI not updating and showing correct user info after signing out and in with differe

Time:12-07

I'm creating and testing a simple dashboard that I want to display the current user's email. I'm just using [email protected] and [email protected]. When I signout of test1 and sign in with test2, my UI still says "Good Evening, [email protected]" when it should be [email protected].

I'm using Firebase Authentication and here is the basic code for displaying the user email(cutting out lots of columns and stuff):

final userEmail = FirebaseAuth.instance.currentUser!.email;

class Dashboard extends ConsumerStatefulWidget {
  const Dashboard({Key? key}) : super(key: key);

  @override
  _DashboardState createState() => _DashboardState();
}

class _DashboardState extends ConsumerState<Dashboard> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
         Padding(
            padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
               child: AutoSizeText(
                  'Good Morning, $userEmail!',
                              ),
                            ),

Then, for signing out I just call a simple Firebase instance.

 ElevatedButton(
                  
                  onPressed: FirebaseAuth.instance.signOut,
                  child: const Text(
                    'Sign Out',
                  ))

The signing out in and works fine with my authentication repo but not sure why the UI isn't updating to current user. I thought this would be enough. I tried adding

  @override
  void dispose() {
    super.dispose();
  }

but that also didn't work.

CodePudding user response:

You are setting the variable right in the starting and it won't update itself after signing out and signing in. You must update it every time a change occurs.

To do so you can add this in initState:

@override
void initState() {
    super.initState();
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
        userEmail = user!.email;
    });
}

And you should also declare the userEmail variable with var instead of final.

  • Related