skip to Main Content

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


  1. Instead of using:

    if (!context.mounted) return;
    

    Try using:

    if (context.mounted) {
    } else {
      return;
    }
    

    It will suppress the warning.

    Login or Signup to reply.
  2. Instead of using:

    if (!context.mounted) return;
    

    Try using:

    if (!mounted) return;
    

    It will also suppress the warning.

    Login or Signup to reply.
  3. 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:

    onPressed: () async {
        final groupID = await database.createGroup();
          if (mounted){}
          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,)),
            );
          }
      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search