Skip to content
This repository was archived by the owner on Nov 20, 2024. It is now read-only.

Commit 85683ba

Browse files
authored
Do not report context.mounted as a use of BuildContext (#4312)
1 parent 4f1d7df commit 85683ba

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

lib/src/rules/use_build_context_synchronously.dart

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ class _AwaitVisitor extends RecursiveAstVisitor {
106106
}
107107

108108
class _Visitor extends SimpleAstVisitor {
109+
static const mountedName = 'mounted';
110+
109111
final LintRule rule;
110112

111113
_Visitor(this.rule);
@@ -238,7 +240,7 @@ class _Visitor extends SimpleAstVisitor {
238240
check = check.identifier;
239241
}
240242
if (check is SimpleIdentifier) {
241-
return check.name == 'mounted';
243+
return check.name == mountedName;
242244
}
243245
if (check is PrefixExpression) {
244246
// (condition || !mounted)
@@ -298,6 +300,11 @@ class _Visitor extends SimpleAstVisitor {
298300

299301
@override
300302
visitPrefixedIdentifier(PrefixedIdentifier node) {
303+
if (node.identifier.name == mountedName) {
304+
// Accessing `context.mounted` does not count as a "use" of a
305+
// `BuildContext` which needs to be guarded by a mounted check.
306+
return;
307+
}
301308
// Getter access.
302309
if (isBuildContext(node.prefix.staticType, skipNullable: true)) {
303310
check(node);

test/rules/use_build_context_synchronously_test.dart

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,40 @@ bool get c => true;
7272
''');
7373
}
7474

75+
test_awaitBeforeIf_mountedExitGuardInIf_beforeReferenceToContext2() async {
76+
// Await, then a proper "exit if not mounted" guard in an if-condition,
77+
// then use of BuildContext, is OK.
78+
await assertNoDiagnostics(r'''
79+
import 'package:flutter/widgets.dart';
80+
81+
void foo(BuildContext context) async {
82+
await f();
83+
if (!context.mounted) return;
84+
Navigator.of(context);
85+
}
86+
87+
Future<void> f() async {}
88+
''');
89+
}
90+
91+
test_awaitBeforeIf_mountedExitGuardInIf_beforeReferenceToContext3() async {
92+
// Await, then a proper "exit if not mounted" guard in an if-condition,
93+
// then use of BuildContext, is OK.
94+
await assertNoDiagnostics(r'''
95+
import 'package:flutter/widgets.dart';
96+
97+
void foo(BuildContext context) async {
98+
await f();
99+
if (!context.mounted) {
100+
return;
101+
}
102+
Navigator.of(context);
103+
}
104+
105+
Future<void> f() async {}
106+
''');
107+
}
108+
75109
test_awaitBeforeIf_mountedGuardInIf1() async {
76110
// Await, then a proper "if mounted" guard in an if-condition, then use of
77111
// BuildContext in the if-body, is OK.

0 commit comments

Comments
 (0)