riverpod icon indicating copy to clipboard operation
riverpod copied to clipboard

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

Open AhmedLSayed9 opened this issue 4 months ago • 1 comments

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 https://github.com/rrousselGit/riverpod/issues/2992 & https://github.com/rrousselGit/riverpod/issues/3744

AhmedLSayed9 avatar Oct 02 '24 22:10 AhmedLSayed9