Here when you call snackbar inside async generally you may notice the warning or error saying that Do not use BuildContexts across async gaps. how to avoid this kind of situation in a class object, not in a widget tree
Asked
Active
Viewed 1,338 times
3
-
Does this answer your question? [Do not use BuildContexts across async gaps](https://stackoverflow.com/questions/68871880/do-not-use-buildcontexts-across-async-gaps) – eamirho3ein Sep 09 '22 at 06:29
-
no you can see there he is using mounted inside widget I am talking only about class and a function imagine if you want call snackbar according to response in api call then I think we can try below answer – Santosh Kumar Sep 09 '22 at 07:08
2 Answers
1
Wrap snackBar code inside a context.mounted
if condition
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}

Peter Musembi
- 19
- 1
0
first I had created a showSnack bar method after that I used future.delay in async to call snackbar I hope this solution will help some one in future those who face this kind of situation following is my function for showSnack bar
void showsnackbar(BuildContext context, String text) {
final snackBar = SnackBar(
content: Text(text),
duration: Duration(seconds: 5),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
following is my async function where I am calling showsnackbar function eg..if you want to show snackbar upon status code then you can do following method
class sample{
Future<void> sample(BuildContext context) async {
switch (res.statusCode) {
case 201:
Future.delayed(Duration.zero)
.then((value) => showsnackbar(context, "sample text"));
}
}
}

Santosh Kumar
- 158
- 1
- 14
-
Add await with Future.delayed(Duration.zero).then((value) => showsnaackbar(context,"Vehicle type inserted")); – Maqsood Sep 09 '22 at 05:20
-