0

I'm getting a warning in one of my Flutter apps in a method that calls an async service.

void _refreshAllOutcomes() {
    confirmPopup(context, 'Refresh all outcomes?').then( (value) {
      if (value) {
        ScaffoldMessenger.of(context).showSnackBar(GdSnackbars.build(
            'Habit tracking', 'Please wait - updating all tracking outcomes', ContentType.help));
        ref.read(habitServiceProvider).refreshAllTrackingOutcomes(_getHabitId()).then( (_) {
          ScaffoldMessenger.of(context).hideCurrentSnackBar();
        });
      }
    });
  }

The logic of the method covers:

  1. Having the user confirm the request in a pop up message
  2. Display a snackbar pop up before the async service call starts
  3. initiate the async service call
  4. When the async service call completes, close the snackbar popup

This code is generating a compile warning that the 'BuildContext' should not be used across async calls.

How should I refactor my code to address this?

Note: I added a mounted check and the compile warning remains.

if (context.mounted) {
  ScaffoldMessenger.of(context).showSnackBar(GdSnackbars.build(
      'Habit tracking', 'Please wait - updating all tracking outcomes', ContentType.help));
}
4
  • use this if (context.mounted) {} Commented Nov 26, 2024 at 12:05
  • 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 Nov 26, 2024 at 12:43
  • That answer you refer to does not remove the compile warning, hence, my question remains valid and different Commented Nov 26, 2024 at 13:08
  • you have this code in statefull widget? Commented Nov 26, 2024 at 14:56

1 Answer 1

2

Don't use if (context.mounted){}

But instead use if (mounted){}

If the widget's context is indirectly used in async calls, it can trigger the warning. Use context.mounted if you specifically need to check the BuildContext after async operations in situations where you suspect the context might have changed or been disposed of.

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

2 Comments

I am using if (context.mounted) {} if I am referring to a method's widget instance that needs to be accessible from a widget tree, where the depth is out of the common parent class instance. Please correct me if I am wrong in explaining this.
Yes correct :) as long as the widgets aren't disposable. Both if(context.mounted) and if(mounted) do the same thing. In user2868835's case, he is passing context to a showSnackBar widget which is disposable. That's why flutter shows an error, it's a warning that you're doing a context.mounted check when the BuildContext could have been disposed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.