Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref.onCancel gets unexpectedly called when a widget rebuilds while using ref.listen #3759

Open
AhmedLSayed9 opened this issue Oct 2, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@AhmedLSayed9
Copy link
Contributor

Describe the bug
When a widget uses ref.listen to listen for a provider and that widget rebuilds, ref.onCancel is getting unexpectedly called. The behavior when using ref.watch works as expected.

To Reproduce

void main() => runApp(const ProviderScope(child: MyApp()));

@riverpod
int foo(FooRef ref) {
  ref.onCancel(() {
    print('onCancel');
  });
  return 0;
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorSchemeSeed: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends ConsumerStatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  ConsumerState<MyHomePage> createState() => _FullScreenScaffoldState();
}

class _FullScreenScaffoldState extends ConsumerState<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    //ref.watch(fooProvider);  This works fine
    ref.listen(fooProvider, (_, __) {});

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Expected behavior
I expect ref.onCancel not to be called.

This might be related to #2992 & #3744

@rrousselGit
Copy link
Owner

The old listener is replaced with a new one. That calls cancel

@rrousselGit rrousselGit added enhancement New feature or request and removed bug Something isn't working needs triage labels Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants