dart-lang/linter

broken `context.mounted` check for `use_build_context_synchronously` (dart 3.5)

Leptopoda opened this issue · 2 comments

Describe the issue
When using the context in a stream listener, the context.mounted does not silence the use_build_context_synchronously lint.

To Reproduce

import 'dart:async';
import 'package:flutter/material.dart';

class Test extends StatefulWidget {
  const Test({super.key});

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  StreamSubscription? subscription;

  @override
  void initState() {
    Stream.periodic(const Duration(seconds: 1)).listen((event) {
      if (context.mounted) {
        ScaffoldMessenger.maybeOf(context)
            ?.showSnackBar(SnackBar(content: Text(event.toString())));
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

Using the suggested context.mounted check does not silence the lint.

Expected behavior
The lint does no longer fire when the context is correctly checked to be mounted.

Additional context
We only face the issue on the latest dart 3.5.
Maybe this helps pin it down to a more recent change.

I think you're supposed to use this.mounted in that check. See the last "Good" example in the docs: https://dart.dev/tools/linter-rules/use_build_context_synchronously

Thanks for the information. I can confirm that this works.