I was getting a warning that said
Don’t use ‘BuildContext’s across async gaps. (Documentation) Try rewriting the code to not reference the ‘BuildContext’.
I clicked on the Documentation link and did what they recommended, which was to add the line if (!context.mounted) return;
(see below). However, I’m still getting the same warning although now it’s pointing to the line I just added. What does this mean and what can I do to code this properly so that the warning doesn’t appear? All I need this button to do is to run some asynchronous work and if it was successful then navigate to a different page.
TextButton(
onPressed: () async {
final groupID = await database.createGroup();
if (!context.mounted) return; //Warning points here
if (groupID == '') {
Fluttertoast.showToast(msg: 'Error creating group');
} else {
groupNameController.clear();
Navigator.of(context).pop(); //Close the dialog box
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScreenChat(groupID: groupID,)),
);
}
},
child: const Text('OK')
),
3
Answers
Instead of using:
Try using:
It will suppress the warning.
Instead of using:
Try using:
It will also suppress the warning.
The error is saying that the user could close the app or go to another page/screen of your app while the async function is still loading/progressing, which would cause an error after its complete because it can’t execute the next line
(if/else)
or check(!context)
.For this reason you need to check if this page/screen is still
mounted
, and if so you’re asking it to continue executing the next lines, or dismiss it. Simply call it this way: