Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Snackbar Error: Don't use 'BuildContext's across async gaps

I am trying to implement a showSnackBar on my App but I am getting this error:

Don’t use ‘BuildContext’s across async gaps.
Try rewriting the code to not use the ‘BuildContext’, or guard the use with a ‘mounted’ check.

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//Post reply
replyThread() async{
  setState(() { _isSubmitted = true; });
  try{
      var res = await http.post(
      Uri.parse(API.quickThreadReplyURL),
        body: {
            'post_id': _postid.toString(),
            'userID': userID.toString(),
            'sessionData': sessionData.toString(),
            'content': contentController.text,
        },
      );
      if(res.statusCode==200){
          //Clear textfield
          contentController.text = '';
          final resBody = jsonDecode(res.body);
          bool success = resBody['success'];
          if(success){
              List thread = resBody['threadList'] as List;
              setState(() {
                threadReplies = thread + threadReplies;
                _isSubmitted = false;
              });
              //Show toaster
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  backgroundColor: Color.fromARGB(255, 139, 247, 92),
                  content: 
                  Text(
                    "New thread reply successfully posted",
                    style: TextStyle(color: Colors.black),
                  ),
                )
              );
          }
          else{
            setState(() { _isSubmitted = false; });
            //Show toaster
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                backgroundColor: Color.fromARGB(255, 240, 96, 96),
                content: 
                Text(
                  "Oops! Something went wrong. Reply not posted",
                  style: TextStyle(color: Color.fromRGBO(255, 255, 255, 1)),
                ),
              )
            );
        }
      }
  }
  catch(e){
    print(e.toString());
  }
}

>Solution :

It is just a warning, but you should fix it. Because after async gaps, BuildContext maybe unmounted:

if (mounted) {
  ScaffoldMessenger.of(context).showSnackBar(...);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading