0

I am facing this issue and didn’t know what to do here

showSnackbar(
        context,
        text: StatusCodes.absenceCancelResponse[statusCode],
        color: Colors.green,
      );

      class StatusCode
      {
        static Map<int, String> absenceCancelResponse = {
              0: "Absence Request Canceled Successfully",
              1: "Error Cancelling Absence Request",
         };
      
      }

Everything working fine but I am annoyed by this warning

Do not use BuildContexts across async gaps 
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Arslan
  • 194
  • 1
  • 10

2 Answers2

2

This has been answered a numerous times here. Just search for it: https://stackoverflow.com/search?q=BuildContexts+across+async+gaps

In short. Use a StatefulWidget. Before the warning, check if the widget is mounted. Do this using if (mounted) { ... } Put the lines where you get the warning inside the curly brackets { }

Update with Flutter 3.7.0

A StatefulWidget is no longer necessary. In a StatelessWidget you can now use context.mounted

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
-1

You need to call code with .then(){}, Which you are using after async code in app.

For ex.,

await provider.getData().then(){
 Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondScreen()));
}
Renik Shiroya
  • 324
  • 4
  • 15