Consumer class final Core

Build a widget tree while listening to providers.

Consumer's main use-case is for reducing the number of rebuilt widgets. when a provider changes.

As an example, consider:

@riverpod
Future<User> fetchUser(Ref ref) async {
  // ...
}

Normally, we would use a ConsumerWidget as followed:

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
     appBar: AppBar(title: Text('User')),
     body: switch (ref.watch(userProvider) {
       AsyncValue(:final value?) => Text(value.name),
       AsyncValue(hasError: true) => Text('Error'),
       _ => CircularProgressIndicator(),
     },
  }
}

However, this would rebuild the entire Scaffold when the user changes. If we are looking to reduce this, have two options:

  • Extract the body into a separate ConsumerWidget. Then only the body will rebuild. This is the recommended approach, but is a bit more verbose.
  • Use Consumer to only rebuild the body when the user changes. This is less recommended, but avoids creating a new widget.

Using Consumer, the resulting code would look like:

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(title: Text('User')),
     body: Consumer(
       builder: (context, ref, child) {
         return switch (ref.watch(userProvider) {
           AsyncValue(:final value?) => Text(value.name),
           AsyncValue(hasError: true) => Text('Error'),
           _ => CircularProgressIndicator(),
         };
       }),
     );
  }
}

Performance considerations

To optimize performance by avoiding unnecessary network requests and pausing unused streams, Consumer will temporarily stop listening to providers when the widget stops being visible.

This is determined using TickerMode.of, and will invoke ProviderSubscription.pause on all currently active subscriptions.

See also:

  • ConsumerWidget, a base-class for widgets that wants to listen to providers.
  • child, a way to optimize the widget tree by passing a child widget that won't rebuild when the provider changes.
Inheritance

Constructors

Consumer.new({Key? key, required ConsumerBuilder builder, Widget? child})
Build a widget tree while listening to providers.
const

Properties

builder → ConsumerBuilder
The builder that will be called when the provider is updated.
final
child Widget?
The child parameter is an optional parameter for the sole purpose of further performance optimizations.
final
hashCode int
The hash code for this object.
no setterinherited
key Key?
Controls how one widget replaces another widget in the tree.
finalinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

build(BuildContext context, WidgetRef ref) Widget
Describes the part of the user interface represented by this widget.
override
createElement() → ConsumerStatefulElement
Creates a StatefulElement to manage this widget's location in the tree.
inherited
createState() → _ConsumerState
Creates the mutable state for this widget at a given location in the tree.
inherited
debugDescribeChildren() List<DiagnosticsNode>
Returns a list of DiagnosticsNode objects describing this node's children.
inherited
debugFillProperties(DiagnosticPropertiesBuilder properties) → void
Add additional properties associated with the node.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) DiagnosticsNode
Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.
inherited
toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) String
A string representation of this object.
inherited
toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) String
Returns a string representation of this node and its descendants.
inherited
toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) String
Returns a one-line detailed description of the object.
inherited
toStringShort() String
A short, textual description of this widget.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited