text
stringlengths
1
474
<topic_end>
<topic_start>Simple app state management
Now that you know about declarative UI programming
and the difference between ephemeral and app state,
you are ready to learn about simple app state management.On this page, we are going to be using the provider package.
If you are new to Flutter and you don’t have a strong reason to choose
another approach (Redux, Rx, hooks, etc.), this is probably the approach
you should start with. The provider package is easy to understand
and it doesn’t use much code.
It also uses concepts that are applicable in every other approach.That said, if you have a strong background in
state management from other reactive frameworks,
you can find packages and tutorials listed on the options page.<topic_end>
<topic_start>
Our example
For illustration, consider the following simple app.The app has two separate screens: a catalog,
and a cart (represented by the MyCatalog,
and MyCart widgets, respectively). It could be a shopping app,
but you can imagine the same structure in a simple social networking
app (replace catalog for “wall” and cart for “favorites”).The catalog screen includes a custom app bar (MyAppBar)
and a scrolling view of many list items (MyListItems).Here’s the app visualized as a widget tree.So we have at least 5 subclasses of Widget. Many of them need
access to state that “belongs” elsewhere. For example, each
MyListItem needs to be able to add itself to the cart.
It might also want to see whether the currently displayed item
is already in the cart.This takes us to our first question: where should we put the current
state of the cart?<topic_end>
<topic_start>
Lifting state up
In Flutter,
it makes sense to keep the state above the widgets that use it.Why? In declarative frameworks like Flutter, if you want to change the UI,
you have to rebuild it. There is no easy way to have
MyCart.updateWith(somethingNew). In other words, it’s hard to
imperatively change a widget from outside, by calling a method on it.
And even if you could make this work, you would be fighting the
framework instead of letting it help you.Even if you get the above code to work,
you would then have to deal
with the following in the MyCart widget:You would need to take into consideration the current state of the UI
and apply the new data to it. It’s hard to avoid bugs this way.In Flutter, you construct a new widget every time its contents change.
Instead of MyCart.updateWith(somethingNew) (a method call)
you use MyCart(contents) (a constructor). Because you can only
construct new widgets in the build methods of their parents,
if you want to change contents, it needs to live in MyCart’s
parent or above.
<code_start>// GOOD
void myTapHandler(BuildContext context) {
var cartModel = somehowGetMyCartModel(context);
cartModel.add(item);
}<code_end>
Now MyCart has only one code path for building any version of the UI.
<code_start>// GOOD
Widget build(BuildContext context) {
var cartModel = somehowGetMyCartModel(context);
return SomeWidget(
// Just construct the UI once, using the current state of the cart.
// ···
);
}<code_end>
In our example, contents needs to live in MyApp. Whenever it changes,
it rebuilds MyCart from above (more on that later). Because of this,
MyCart doesn’t need to worry about lifecycle—it just declares
what to show for any given contents. When that changes, the old
MyCart widget disappears and is completely replaced by the new one.This is what we mean when we say that widgets are immutable.
They don’t change—they get replaced.Now that we know where to put the state of the cart, let’s see how
to access it.<topic_end>
<topic_start>
Accessing the state
When a user clicks on one of the items in the catalog,
it’s added to the cart. But since the cart lives above MyListItem,
how do we do that?A simple option is to provide a callback that MyListItem can call
when it is clicked. Dart’s functions are first class objects,
so you can pass them around any way you want. So, inside
MyCatalog you can define the following:
<code_start>@override
Widget build(BuildContext context) {
return SomeWidget(
// Construct the widget, passing it a reference to the method above.
MyListItem(myTapCallback),
);
}
void myTapCallback(Item item) {
print('user tapped on $item');
}<code_end>
This works okay, but for an app state that you need to modify from
many different places, you’d have to pass around a lot of
callbacks—which gets old pretty quickly.Fortunately, Flutter has mechanisms for widgets to provide data and
services to their descendants (in other words, not just their children,
but any widgets below them). As you would expect from Flutter,
where Everything is a Widget™, these mechanisms are just special
kinds of widgets—InheritedWidget, InheritedNotifier,
InheritedModel, and more. We won’t be covering those here,
because they are a bit low-level for what we’re trying to do.Instead, we are going to use a package that works with the low-level
widgets but is simple to use. It’s called provider.Before working with provider,
don’t forget to add the dependency on it to your pubspec.yaml.To add the provider package as a dependency, run flutter pub add:Now you can import 'package:provider/provider.dart';
and start building.With provider, you don’t need to worry about callbacks or
InheritedWidgets. But you do need to understand 3 concepts:<topic_end>
<topic_start>
ChangeNotifier
ChangeNotifier is a simple class included in the Flutter SDK which provides
change notification to its listeners. In other words, if something is
a ChangeNotifier, you can subscribe to its changes. (It is a form of
Observable, for those familiar with the term.)In provider, ChangeNotifier is one way to encapsulate your application