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

Do not trigger use_build_context_synchronously on context.mounted #4134

Merged

Conversation

kzrnm
Copy link
Contributor

@kzrnm kzrnm commented Mar 12, 2023

Description

Do not trigger use_build_context_synchronously on context.mounted.

Fixes dart-lang/sdk#59009 partially.

Fixed

class AsyncContextTestWidget extends StatelessWidget {
  const AsyncContextTestWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        await Future<void>.delayed(Duration.zero);

        // This line is marked as using context across async gaps
        if (!context.mounted) {
          return;
        }
      },
      child: const Text('Test'),
    );
  }
}

Not fixed

// This line triggers a warning too
final isMounted = context.mounted;

if (!isMounted) {
  return;
}

@google-cla
Copy link

google-cla bot commented Mar 12, 2023

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@github-actions github-actions bot added the linter-set-flutter Affects a rule in the recommended Flutter rule set label Mar 12, 2023
@coveralls
Copy link

Coverage Status

Coverage: 95.581% (+0.0005%) from 95.58% when pulling a06ce3c on kzrnm:fix/use_build_context_synchronously-/4007 into b3fb9e5 on dart-lang:main.

Copy link

@kj415j45 kj415j45 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me.

The not-fixed example you provided is against the lint.

Storing BuildContext for later usage can easily lead to difficult to diagnose crashes.

When a BuildContext is used, its mounted property must be checked after an asynchronous gap.

Consider the following code smell.

// Storing BuildContext.mounted
final isMounted = context.mounted;

// For developers unaware of this lint
// may insert some code here like below
await doSomething();

if (!isMounted) { // break the mounted guard
  return;
}

Copy link
Contributor

@srawlins srawlins left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love it, thanks for the test.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
linter-false-positive linter-set-flutter Affects a rule in the recommended Flutter rule set
Development

Successfully merging this pull request may close these issues.

use_build_context_synchronously is triggered when using context.mounted
4 participants