Is it ok to nest ConsumerWidgets in riverpods?

Viewed 269

In Riverpods, is it ok to nest ConsumerWidgets? Something like this? I want to do so to keep my apis separated, but it feels like it might slow down performance?

class Foo1 extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    // watch something
    return Container(
      child: Foo2(),
    );
  }
}

class Foo2 extends ConsumerWidget {
  @override
    // watch something
  Widget build(BuildContext context, ScopedReader watch) {
    return Container();
  }
}
1 Answers

This is completely and totally fine. It would not be strange if most or all widgets in your application were ConsumerWidgets.

As long as you only watch providers when/where needed, you have nothing to be concerned about.

There are many ways to optimize rebuilds. For example, creating providers that only expose one aspect of state your widget may depend on or using Consumer to only rebuild certain children when the value exposed by a provider changes. If you're using hooks, you can use select which is super handy for conditionally rebuilding.

Related