1

I have an API call inside my flutter application. After that API returned, I need to navigate to other screen, but a warning is shown:

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.

How can I do this?

This is the API call code:

               apiService.checkOTP(_emailController.text, s).then((profile) async {
                  if (profile != null) {
                    SharedPreferences sp = await SharedPreferences.getInstance();
                    ......
                    Navigator.push(context,
                                      MaterialPageRoute(builder: (context) => MyHomePage(title: GlobalConstants.appName)));
                    // Store the profile data or navigate to the next screen
                    // For example, you can save the profile in shared preferences or a state management solution
                    return null; // Indicating that the OTP is valid
                    
                  }
                }).catchError((error) {
                  showMessage(state, ContentType.failure, '¡Error!', 'error message.');
                });
1
  • This question is similar to: Do not use BuildContexts across async gaps. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 28 at 4:12

3 Answers 3

2

It means pretty much what it says. You have "await.... context", and that pattern can blow up if the widget gets unmounted during the await. The docs actually have examples of bad and good code: https://dart.dev/tools/linter-rules/use_build_context_synchronously

Sign up to request clarification or add additional context in comments.

Comments

0

Convert the then chain to async-await for better readability and context safety.
Add a StatefulWidget and use if (!mounted) return; before using context.

Example:

final profile = await apiService.checkOTP(_emailController.text, s);
if (profile != null) {
  if (!mounted) return;
  Navigator.push(context, MaterialPageRoute(...));
}

Comments

0

BuildContext is your key to add widgets to the tree and to perform actions like navigation.
Since you are calling it inside a async function that key maybe no longer valid.

For example, if you call it from a widget and that widget was removed from the tree, the associated context is also removed.*

To avoid that you need to check if the context is still valid. Flutter provide a simple thing to do this (inside stateful clases)

  if (mounted){
//PERFORM YOUR ACTION
}

or even better just stop any further action if context is invalid

  if (!mounted) return;

With this you can check before doing your action and ensure is always a valid context

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.