Search code examples
flutterdart

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:

//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(...);
    }