firebaseflutterdartemail-verification

email verification not working in flutter firebase


Here i am calling my home in main.dart Now if i am not verify my email it is still redirecting me to my First_Page instead of Sign_In_Page.

 home: FirebaseAuth.instance.currentUser?.emailVerified==null?Sign_In_Page():First_Page(),

This is my email verifaication page which i am navigating after user signup with a email id and passowrd

  final auth=FirebaseAuth.instance;
  late User user;
  late Timer timer;
  @override
  void initState() {
   user=auth.currentUser!;
   user.sendEmailVerification();
   timer=Timer.periodic(Duration(seconds: 5), (timer) {
     emailverify();
   });
    super.initState();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          child: Text(
            "An Email verification link has been sent to you, Please verify..",
            style: TextStyle(fontSize: 20,color: Colors.black),
          ),
        ),
      ),
    );
  }
   Future<void> emailverify() async{
    user=auth.currentUser!;
    await user.reload();
    if(user.emailVerified){
      timer.cancel();
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>First_Page()));
    }
}
}

I am getting the email for verification but if i didn't verify it, it still redirecting me to my app. I think there is some problem in my code. Plz help me in correcting it.


Solution

  • Shortly the problem is in your check for email verification. It should be

    (FirebaseAuth.instance.currentUser?.emailVerified ?? false) ? First_Page() : Sign_In_Page()
    

    Your code was checking whether the optional emailVerified is not null, it would work only if no user is authenticated as it will be null as currentUser is null. But if a user already exists even if he's not verified the result will not be equal to null and your check fails and goes to app page.