How to call snackbar inside async method?

Viewed 42

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

1 Answers

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"));
          }
    }
}
Related