Search code examples
firebaseflutterdartfirebase-authenticationstream-builder

snapshot.data.emailVerified not changing the screen in realtime after the email has been verified by user flutter firebase


I want to navigate to Homescreen in real time after the email is verified by the user but after the user has verified their email it still remains on VerifyEmailScreen.

Till now i am able to navigate to LoginScreen and HomeScreen in realtime only when user signout or signin

I tried to reload to the user after 3 but it is still at EmailVerification Screen .....please help

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Timer timer;
  @override
  void initState() {
    timer = Timer(Duration(seconds: 3), () {
      FirebaseAuth.instance.currentUser.reload();
    });
    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      child: MaterialApp(
          darkTheme: ThemeData(
            brightness: Brightness.dark,
          ),
          themeMode: ThemeMode.dark,
          debugShowCheckedModeBanner: false,
          home: LandingPage()
      ),
      providers: [
        ChangeNotifierProvider(create: (_)=>FirebaseMethods()),
        ChangeNotifierProvider(create: (_)=>ProfileScreenUtils())
      ],
    );
  }
}

class LandingPage extends StatelessWidget {

  //final FirebaseRepository _repository = FirebaseRepository();
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, AsyncSnapshot<User> snapshot) {
            if (snapshot.hasData) {
           // print("USER ID IF USER IS NOT NULL :  " + user.uid);
              if(snapshot.data.emailVerified)
                {
                  return HomeScreen();
                }
              else
                {
                  return VerifyEmailScreen();
                }
            }
            else if(snapshot.hasError)
              {
                return CircularProgressIndicator();
              }
            else {
              //print("USER ID IF THE USER IS NULL :  " + user.uid);
              return LoginScreen();
            }
      },
    );
  }
}

Solution

  • When the user verifies the email, authStateChanges is not called. You should call FirebaseAuth.instance.currentUser.reload(); to get the refreshed data of the user. You can do it using a polling request, every second for example:

    Timer timer = Timer(Duration(seconds: 1), () {
      FirebaseAuth.instance.currentUser.reload();
    });
    

    Or you can add a button, where the user clicks when the email is verified.