I have a simple statefullWidget like this:
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late String _email;
void getEmail() async {
-> doing stuff and **set the value of _email**
}
@override
void initState() {
super.initState();
getEmail(); //I invoke the method during the initstate()
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Text(_email);
),
);
}
}
Doing this I get an exception saying me that the value of email is null. I thought that the method initState() was called before the build method, but maybe I am wrong.
Do you have and idea to how to solve my problem?
P.S. If I declare the variable _email like this:
String _email = '';
my UI starts with a blank space and then is filled with the correct value of the email. I don't want that, though.
In this modification, I introduced a separate method _initializeState that calls getEmail and then updates the state using setState only if the widget is still mounted. This ensures that the UI is updated only when the asynchronous operation is completed.