Search code examples
flutterdartflutter-layoutflutter-webdart-null-safety

how to solve BuildContexts across async gaps error flutter


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 

Solution

  • 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