Search code examples
flutterriverpodflutter-riverpod

Flutter Riverpod, build() is not getting called after changing the state


Minimal reproducible code:

final fooProvider = StateProvider<int>((ref) => 0);

final barProvider = Provider<String>((ref) {
  ref.watch(fooProvider); // 1
  return '';
});

class FooPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: BarPage(),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(fooProvider.notifier).state++, // 2
      ),
    );
  }
}

class BarPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    print('build(BarPage)'); // 3
    final string = ref.watch(barProvider); // 4
    return Text(string);
  }
}

1: barProvider is watching fooProvider.

2: I am changing fooProvider state.

4: I am watching barProvider (which itself is watching fooProvider, see 1)

3: This should have printed but it didn't.


Solution

  • The value returned by your provider is always ''

    As such, Provider detects that the value exposed did not change, and does not notify listeners.

    If you placed a print inside barProvider, you would see that the provider got rebuilt.