dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
628 stars 172 forks source link

'BuildContext's across async gaps false positive? #4955

Closed stephane-archer closed 2 months ago

stephane-archer commented 2 months ago
                      if (context.mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(snackBar);
                      }

ok but:

                      if (context.mounted == false) {
                        return;
                      }
                      ScaffoldMessenger.of(context).showSnackBar(snackBar);

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.

srawlins commented 2 months ago

A possible gap in the rule! I think this doesn't come up because it is more idiomatic to write if (!context.mounted).

srawlins commented 2 months ago

Actually I cannot reproduce this at HEAD. Can you say what version of Dart/Flutter you are using, and provide a more full example (just the full function body there should be sufficient).

srawlins commented 2 months ago

Oops, apologies. I can reproduce. :D

stephane-archer commented 2 months ago

@srawlins no worries The idiomatic way would fail silently or need an else close to handle the error which is quite verbose I'm not sure why it's the idiomatic way :)

if (context.mounted == false) {
                        throw "I don't fail silently!";
 }
ScaffoldMessenger.of(context).showSnackBar(snackBar);
srawlins commented 2 months ago

Hmm, I might have not been clear. I mean that the idiomatic way to write context.mounted == false is !context.mounted.

stephane-archer commented 2 months ago

@srawlins ho I see, I misunderstood what you meant, sorry. I hope to allow context.mounted == false would be easy to add.

srawlins commented 2 months ago

Fixed with https://github.com/dart-lang/sdk/commit/d728ec3c65aeafe4c1559e1875c5f09e1e6573a9

stephane-archer commented 2 months ago

@srawlins you are the best 🤯