im trying to authenticate users using flutter and firebase. Once a user creates his account, he’s redirected to the email verification screen where he should follow the link sent to his email. After that, his name will be displayed on the home screen after verification.
The problem is that i’m always getting the following error: setState() called after dispose() whenever I try to get his firstname and lastname from the cloud firestore.
Here is my code:
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final user = FirebaseAuth.instance.currentUser;
String? firstname;
String? lastname;
void getData() {
FirebaseFirestore.instance
.collection('users')
.doc(user!.uid)
.snapshots()
.listen((data) {
setState(() {
firstname = data.data()!['nom'];
lastname = data.data()!['prenom'];
});
});
}
@override
void initState() {
getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 12.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [Text('Hello,', style: GoogleFonts.lato())],
),
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.only(left: 12),
child: Text('${firstname} ${lastname}'.toUpperCase(),
style: GoogleFonts.lato(
fontSize: 20, fontWeight: FontWeight.bold)),
)]));
I tried several solutions found on the net but couldn’t solve the problem, the only solution that worked for me was delaying the timer for the email verification.
Can anyone help me out with the issue? thanks in advance!
2
Answers
Try
and remove the setState in getData. Assign the values directly to the variable
You can check boolean property
mounted