I tried adding email verification logic in my flutter app with the help of firebase authentication. Now the issue I am facing is, that it works sending the verification mail via user.sendEmailVerification()
, but the method user.emailVerified yeels false.
And also the code which should be runned if the mail is verified doesnt run. The weird thing now is, that when I am File save the code in VS CODE (Strg + S), I am getting lead to the page where I should land when the email is verified (with the StreamBuilder in main.dart which checks if FirebaseAuth.instance.authStateChanges()):
enter image description here
I am trying to do it this way:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../screens/home_screen.dart';
class VerifyMailScreen extends StatefulWidget {
final User _user;
VerifyMailScreen(this._user);
@override
_VerifyMailScreenState createState() => _VerifyMailScreenState();
}
class _VerifyMailScreenState extends State<VerifyMailScreen> {
final auth = FirebaseAuth.instance;
Timer? timer;
@override
void initState() {
super.initState();
print(widget._user.email.toString());
widget._user.sendEmailVerification();
timer = Timer.periodic(Duration(seconds: 5), (timer) {
_checkEmailVerified();
});
}
Future<void> _checkEmailVerified() async {
await widget._user.reload();
if (widget._user.emailVerified) {
timer!.cancel();
Navigator.of(context).pushNamed(HomeScreen.routeName);
}
print(widget._user.email);
print(widget._user.emailVerified);
}
@override
void dispose() {
super.dispose();
timer!.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
actions: [
IconButton(
onPressed: () {
auth.signOut();
},
icon: Icon(Icons.logout),
color: Theme.of(context).textTheme.headline6!.color)
],
title: Text(
"Verify your mail",
style: Theme.of(context).textTheme.headline6,
),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Verification screen"),
ElevatedButton(
onPressed: _checkEmailVerified, child: Text("Retry")),
],
),
),
);
}
}