Consumer<T> class
Obtains Provider<T> from its ancestors and passes its value to builder.
The Consumer widget doesn't do any fancy work. It just calls Provider.of
in a new widget, and delegates its build implementation to builder.
builder must not be null and may be called multiple times (such as when the provided value change).
The Consumer widget has two main purposes:
- It allows obtaining a value from a provider when we don't have a BuildContext that is a descendant of said provider, and therefore cannot use Provider.of.
This scenario typically happens when the widget that creates the provider is also one of its consumers, like in the following example:
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Foo(),
child: Text(Provider.of<Foo>(context).value),
);
}
This example will throw a ProviderNotFoundException, because Provider.of is called with a BuildContext that is an ancestor of the provider.
Instead, we can use the Consumer widget, that will call Provider.of with its own BuildContext.
Using Consumer, the previous example will become:
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Foo(),
child: Consumer<Foo>(
builder: (_, foo, __) => Text(foo.value),
},
);
}
This won't throw a ProviderNotFoundException and will correctly build the
Text. It will also update the Text whenever the value foo changes.
- It helps with performance optimization by providing more granular rebuilds.
Unless listen: false is passed to Provider.of, the widget
associated with the BuildContext passed to Provider.of will rebuild
whenever the obtained value changes. This is the expected behavior,
but sometimes it may rebuild more widgets than needed.
Here's an example:
@override
Widget build(BuildContext context) {
return FooWidget(
child: BarWidget(
bar: Provider.of<Bar>(context),
),
);
}
In the above code, only BarWidget depends on the value returned by
Provider.of. But when Bar changes, then both BarWidget and
FooWidget will rebuild.
Ideally, only BarWidget should be rebuilt. One
solution to achieve that is to use Consumer.
To do so, we will wrap only the widgets that depends on a provider into a Consumer:
@override
Widget build(BuildContext context) {
return FooWidget(
child: Consumer<Bar>(
builder: (_, bar, __) => BarWidget(bar: bar),
),
);
}
In this situation, if Bar were to update, only BarWidget would rebuild.
But what if it was FooWidget that depended on a provider? Example:
@override
Widget build(BuildContext context) {
return FooWidget(
foo: Provider.of<Foo>(context),
child: BarWidget(),
);
}
Using Consumer, we can handle this kind of scenario using the optional
child argument:
@override
Widget build(BuildContext context) {
return Consumer<Foo>(
builder: (_, foo, child) => FooWidget(foo: foo, child: child),
child: BarWidget(),
);
}
In that example, BarWidget is built outside of builder. Then, the
BarWidget instance is passed to builder as the last parameter.
This means that when builder is called again with new values, a new
instance of BarWidget will not be created.
This lets Flutter know that it doesn't have to rebuild BarWidget.
Therefore in such a configuration, only FooWidget will rebuild
if Foo changes.
Note:
The Consumer widget can also be used inside MultiProvider. To do so, it
must return the child passed to builder in the widget tree it creates.
MultiProvider(
providers: [
Provider(create: (_) => Foo()),
Consumer<Foo>(
builder: (context, foo, child) =>
Provider.value(value: foo.bar, child: child),
)
],
);
See also:
- Inheritance
-
- Object
- DiagnosticableTree
- Widget
- StatelessWidget
- SingleChildStatelessWidget
- Consumer
- Implemented types
- Available extensions
Constructors
- Consumer({Key? key, required Widget builder(BuildContext context, T value, Widget? child), Widget? child})
- Consumes a Provider<T>
Properties
- builder → Widget Function(BuildContext context, T value, Widget? child)
-
Build a widget tree based on the value from a Provider<T>.
final
- elHorizontalScroll → Widget
-
Available on Widget, provided by the ElWidgetExt extension
监听鼠标水平滚动(仅限桌面端生效),其后代滚动小部件必须在 widget 层指定 ScrollControllerno setter - 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) → Widget -
Describes the part of the user interface represented by this widget.
inherited
-
buildWithChild(
BuildContext context, Widget? child) → Widget -
A build method that receives an extra
childparameter.override -
createElement(
) → SingleChildStatelessElement -
Creates a StatelessElement to manage this widget's 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
-
elScrollbarBehavior(
BuildContext context, ElScrollBehavior behavior) → Widget -
Available on Widget, provided by the ElWidgetExt extension
合并祖先 ElScrollBehavior 的默认配置,如果不需要尊重祖先配置, 请直接使用 ScrollConfiguration 覆盖即可 -
noScrollbarBehavior(
BuildContext context, {Key? key, bool? overscroll, Set< PointerDeviceKind> ? dragDevices, MultitouchDragStrategy? multitouchDragStrategy, Set<LogicalKeyboardKey> ? pointerAxisModifiers, ScrollPhysics? physics, TargetPlatform? platform, ScrollViewKeyboardDismissBehavior? keyboardDismissBehavior, bool enabled = true}) → Widget -
Available on Widget, provided by the ElWidgetExt extension
不使用祖先提供的默认滚动条,当使用自定义滚动条时请设置此扩展,可以防止与祖先提供的默认滚动条重叠 -
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