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

Commit 1a3af7b

Browse files
authored
update use_build_context_synchronously for BuildContext.mounted (#3689)
1 parent a3eeb86 commit 1a3af7b

File tree

3 files changed

+7
-14
lines changed

3 files changed

+7
-14
lines changed

lib/src/rules/use_build_context_synchronously.dart

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ Storing `BuildContext` for later usage can easily lead to difficult to diagnose
2020
crashes. Asynchronous gaps are implicitly storing `BuildContext` and are some of
2121
the easiest to overlook when writing code.
2222
23-
When a `BuildContext` is used from a `StatefulWidget`, the `mounted` property
24-
must be checked after an asynchronous gap.
23+
When a `BuildContext` is used, its `mounted` property must be checked after an
24+
asynchronous gap.
2525
2626
**GOOD:**
2727
```dart
@@ -40,15 +40,11 @@ void onButtonTapped(BuildContext context) async {
4040
4141
**GOOD:**
4242
```dart
43-
class _MyWidgetState extends State<MyWidget> {
44-
...
45-
46-
void onButtonTapped() async {
47-
await Future.delayed(const Duration(seconds: 1));
43+
void onButtonTapped() async {
44+
await Future.delayed(const Duration(seconds: 1));
4845
49-
if (!mounted) return;
50-
Navigator.of(context).pop();
51-
}
46+
if (!context.mounted) return;
47+
Navigator.of(context).pop();
5248
}
5349
```
5450
''';

test_data/mock_packages/flutter/lib/src/widgets/framework.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ typedef void VoidCallback();
99

1010
abstract class BuildContext {
1111
Widget get widget;
12+
bool get mounted;
1213
RenderObject? findRenderObject();
1314
}
1415

test_data/rules/use_build_context_synchronously.dart

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@
77
import 'package:flutter/foundation.dart';
88
import 'package:flutter/widgets.dart';
99

10-
extension on BuildContext {
11-
bool get mounted => false;
12-
}
13-
1410
void mountedBinOpAnd(BuildContext context, bool condition) async {
1511
await Future<void>.delayed(Duration());
1612
if (condition && context.mounted) {

0 commit comments

Comments
 (0)