-
Notifications
You must be signed in to change notification settings - Fork 906
Provider
A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.
To expose a variable using provider, wrap any widget into one of the provider widgets from this package and pass it your variable. Then, all descendants of the newly added provider widget can access this variable.
A simple example would be to wrap the entire application into a Provider widget and pass it our variable:
Provider<Foo>.value(
value: foo,
child: someWidget,
)
The easiest way to read a value is by using the static method Provider.of(BuildContext context). This method will look up in widget tree starting from the widget associated with the BuildContext passed and it will return the nearest variable of type T found (or throw if nothing if found).
Combined with the first example of exposing a value, this widget will read the exposed String and render "Hello World."
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
/// Don't forget to pass the type of the object you want to obtain to `Provider.of`!
Provider.of<Foo>(context)
);
}
}
Alternatively instead of using Provider.of, we can use the Consumer widget.
This can be useful for performance optimizations or when it is difficult to obtain a BuildContext descendant of the provider.
Center(
child: Consumer<Foo>(
builder: (context, value, child) => Text(value),
),
);
You can read more about provider from the following link: Provider