In my Log in Screen, I encounter a problem due to BuildContext within an async block. When user wlick on "Log in" button (Se connecter in French) : I start an async procedure (check connectivity, check if user credentials are ok...) but I also open "dialog boxes" to display loading indicator, or a sort of a popup (My alert info) to tell user if there was a problem. I get indication that I shouldn't use "context" when inside an async clock.
Container(
margin: const EdgeInsets.only(right: 10),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size(20, 45),
backgroundColor: Colors.blue[900],
foregroundColor: Colors.white,
),
onPressed: () async {
if (await _connectivity.checkConnectivity() ==
ConnectivityResult.none) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text(
'Oops... ',
style: TextStyle(fontSize: 22.0),
),
content: const Text(
'Il faut te connecter à Internet !',
style: TextStyle(fontSize: 18.0),
),
actions: [
TextButton(
onPressed: () {
Navigator.pushReplacementNamed(
context, StartingScreen.id);
},
child: const Text(
'OK',
style: TextStyle(fontSize: 18.0),
),
),
],
),
);
} else {
DialogBuilder(context).showLoadingIndicator(
heading: 'Patientez ...',
text: 'Téléchargement des bases',
color: Colors.black45);
String accountVerif =
await uD.checkAccountId(
emailController.text,
passWordController.text);
print('Voici Account Verif : $accountVerif');
if (accountVerif == '') {
await uD.downLoadUserInfo();
final prefs =
await SharedPreferences.getInstance();
prefs.setString('email',
emailController.text.toLowerCase());
prefs.setString(
'passWord', passWordController.text);
DialogBuilder(context).hideOpenDialog();
Navigator.pushReplacementNamed(
context, HomeScreen.id);
} else {
setState(() {
emailController.clear();
passWordController.clear();
});
Navigator.pop(context);
// myAlertInfo(context,
// icone: Icons.warning,
// alerte: 'Oops... ',
// text:
// 'Ce compte n\'existe pas, ou le mot de passe est incorrect.',
// bouton1: 'OK',
// function1: () =>
// Navigator.pop(context));
}
}
},
child: Text('Se connecter',
style: TextStyle(fontSize: uD.mediumFont))),
),
How could I review the code to prevent this problem ? Thanks for your help :)