child property

Widget? child
final

The child parameter is an optional parameter for the sole purpose of further performance optimizations.

If your builder function contains a subtree that does not depend on the animation, it is more efficient to build that subtree once instead of rebuilding it on every provider update.

If you pass the pre-built subtree as the child parameter, the Consumer will pass it back to your builder function so that you can incorporate it into your build.

Using this pre-built child is entirely optional, but can improve performance significantly in some cases and is therefore a good practice.

This sample shows how you could use a Consumer

final counterProvider = NotifierProvider<Counter, int>(Counter.new);
class Counter extends Notifier<int> {
  @override
  int build() => 0;

  void increment() => state++;
}

class MyHomePage extends ConsumerWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title)
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Consumer(
              builder: (BuildContext context, WidgetRef ref, Widget? child) {
                // This builder will only get called when the counterProvider
                // is updated.
                final count = ref.watch(counterProvider);

                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Text('$count'),
                    child!,
                  ],
                );
              },
              // The child parameter is most helpful if the child is
              // expensive to build and does not depend on the value from
              // the notifier.
              child: Text('Good job!'),
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.plus_one),
        onPressed: () => ref.read(counterProvider.notifier).increment(),
      ),
    );
  }
}

Implementation

final Widget? child;