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());
}
}
3
Answers
You could check async logic like below:
Refer the following link:
https://dart.dev/tools/linter-rules/use_build_context_synchronously
It is just a warning, but you should fix it. Because after async gaps, BuildContext maybe unmounted:
I would like to suggest instead of passing BuildContext context in a snckbar, use the below solution which may be fix your issue of async gaps
1.Create one snackbar_utils.dart file and add this in your existing project.
// Add this line into your MaterialApp
//usage :