Managing State in Flutter

Sep 22 2022 · Dart 2.17, Flutter 3.0, Android Studio Chipmunk

Part 2: Use Provider

12. Use Context Methods

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Use a Change Provider Next episode: 13. Understand Consumers

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 12. Use Context Methods

So far, we’ve getting our model objects by calling the Provider.of method. This gives us access to our model object, but Provider has actually made getting our objects far easier. By using extension methods, we don’t need to call Provider.of, we can use extension methods defined on the context. There are three methods available to us.

The first method is the read method. This just gets the value much like with the simple provider. It does not respond to state changes. This means, you should never use a a read method inside of a build method. This is suited for things like event handlers.

This extension method is shorthand for this variation of the Provider.of method.

If you do want to respond to state updates, you use the watch method. The watch method will trigger state rebuilds. This is comparable to the following method.

Finally, there is the Select method allows you to watch to specific properties of an object.

Say you had a character that a hit points property and a strength property. If you were only interested in the hit points property, you would you use select. This means, the widget will only respond to hit point changes. If the strength changes, the widget will not rebuild. Unlike the other context methods, there is no Provider.of equivalent. The method signature contains two types - one for the type that holds the property and another for the property type itself.

Open your project in progress or download the starter project. We’re going to change all of our Provider.of methods into watch methods. This is actually pretty easy to do. First, open tutorals_page.dart. Update the call to fetch the pillar to the following:

final pillar = context.watch<Pillar>();

Next, open tutorial_widget.dart and do the same:

final pillar = context.watch<Pillar>();

Build and run. The app runs exactly the same except now our code is easier to understand.