Flutter Provider: The Essential Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to this video series on the provider package in the last video we took at first glance at the provider package and we have seen how to use it to add flavors to a sample flatter application and in this video we will take a step forward and refactor the counter example up to use provider and while doing this we will capture the essence of what provider is all about because we will learn how to use it as a state management technique we will understand how to use provider and the consumer widget and we will also cover change notifier and value notify as an effective technique for state management that scales across multiple widgets so this video really is an essential guide to provider and if this is useful please like and subscribe so that you can improve your flutter skills okay so let's get started with a recap of how fluttered obligations are built and what I have here is a widget tree for the example counter up and normally we have a widget at the top which represents the entire application and then we have a material up which is a convenience widget that we always need if our application uses material design and then we have some arrangement of widgets which depends on how our app is structured and this diagram shows the widget tree for the flutter counter example which is running over here and the way this counter up works is that when we press the floating action button then we update a counter variable inside a call to set state and this entire widget rebuilt as a result along with all these descendants causing the text inside this widget to show the updated counter value and this approach works well here because this is a simple use case where all the state management logic can live inside a single widget class which is a stateful widget but there are times where we deal with much more complex widget hierarchies and we need to propagate State across different widget classes for example here we have a producer widget which can emit some events and change some internal application state and there are one or more recent of widgets that need to repeat themselves when the state changes and to accomplish this we could use a technique called lifting state up the idea here is to use a stateful widget as the first common ancestor of all these widgets and then we can propagate the state changes from this widget all the way up to the common ancestor and called sat state at this level and this will cause a rebuild of the listeners as well as all these other widgets however this approach doesn't scale well and requires a lot of boilerplate code and it is also inefficient because when this widget rebuilds then all these descendants rebuild as well and this is one example web provider comes to the rescue so what we can do here is to add a provider as a common ancestor to all this widget and with this setup the producer widget can find that provider that it needs and update the state and the listener we just can register themselves for updates so that they can rebuild when the state changes now one thing that I want to make clear is that this provider is a common ancestor to all the widgets inside this subtree so any of these widgets can get access to the provider but only the widgets that have registered themselves as listeners will rebuild when the state changes on the other hand this widget over here on the Left does not have access to the provider because it doesn't have it as an ancestor so the bottom line is that every time we create a new provider we need to decide where it should go on the widget tree depending on who needs access to it and we will talk more in detail about this in a future video ok so let's see how to apply all of this theory to our example so our next goal is to refactor the counter example up to use provider and by the way we must not forget to install provider as a dependency in our pub spec Toyama file and here I'm doing this with the pub spec is's extension of Visual Studio code okay so now that provider has been installed I can save the file and get the latest packages and then I can get back to the main file and as you can see in the current implementation we have a counter that holds the value that we want to show and because this value can change then we need to use a stateful widget so that we can call set State when we to rebuild our widget and what we want to do instead is to define a provider with a new counter class which holds the counter value and can be updated when the floating action button is pressed and then we want to register this text widget as a listener so that it can rebuild itself when the counter changes and as we will see once we are done with our factor then this widget will become stateless okay so let's start by creating a new counter class so over here I'm going to create a new dart file called counter Bob dart and here I can define a class counter and inside it I can create an int value with an initial value of zero and then we can add a new void increment method that we can use to increment our value so as it is this class holds our counter value and we can increment it by calling this method however we also need a way for this class to notify its listeners when the counter is updated and to do this we can use a class called change notifier and this can be either implemented or added as a mixing to existing classes so in this case we can type with change notifier to add this as a mixing to our country class and we need to import foundation tart in order to use this and with this change we can call the methods of change notifier from inside our counter class and this means that we can call a method called notify listeners when the counter is updated and with this change our counter cross is complete next we can head back to our main file and what we want to do is to add a parent provider to this widget so in this case we can wrap a new widget and here we are going to use a change notifier provider of type counter and to use this we need to import provider and also counter dot start and this is a special kind of provider that is designed to work with change notifier and this provider takes my home page as a child widget but it also needs to specify a builder argument and this is a closure that takes a context and we can use this to return a counter like this and I can quickly format my code as well okay so by writing this code we have inserted a provider as the parent of the my home page widget okay so now that we have a parent provider how can we use it well if we go down to the build method here I can delete these lines and instead I can get my counter by typing final counter equals provider the off with type counter of context like this and then we can locate the text widget that shows the counter value and we can replace this with counter value inside curly braces and also we can update the on pressed call back of the floating action button by calling counter the increment like this and now that we have made these changes we can see that the old counter variable and this method are no longer needed so we can delete all this code and since we no longer have any mutable state in this widget class we can convert it to a stateless widget instead so here I can just change this to States let's widget and also I can remove all these lines from here and after making this change I can replace widget title with just title because I can access this instance variable directory and this is all we needed to do to refactor our counter example so at this stage we can hot restart our application and the counter has been reset to zero and we can see that when we press this button then the counter text is updated and while this works maybe is not entirely clear why the text updates after all we have just removed all calls to set state so how does this widget know that it needs to rebuild itself and the answer is that when we call provider of counter with context not only we get the counter object but we are also registering the current widget as a listener to this provider so let me say this once again when we call provider dot of insider widget not only we get access to the value that we want but we also register that widget as a listener and what this means is that my home page completely rebuilds itself every time the counter changes because my home page is now a listener for this counter cross and this works but it's inefficient because it means that all the descendant widgets of my home page also rebuild themselves even though they are not affected by the counter change and if we want to avoid this we can get back to our provider dot of coal and here we can add a new argument called listen and we can give it a value of false like this and when we do this we still get the counter value but we no longer register the current widget as a listener for the counter and if we hot press start the counter is reset and we can see that if we press on this button then the text value no longer changes because our widget is no longer a listener and the build method is no longer called when the state changes okay so what we really want to do here is to only rebuild this text widget when the counter changes and to do that we need to introduce a new widget called consumer and a consumer is a widget inside the provider package that is used to register itself as a listener so let's see how to use consumer in practice and over here we can locate our text widget and then we can wrap this with a new widget and this is going to be a consumer of pipe counter like this and here we don't want to use the child argument but instead we will give it a builder which is a closure that takes a context and a counter and that child and we want to use this to return our text widget and just to be clear the counter variable that we are using here now comes from the argument of our builder and with this change we can save and hot reload and we can see that when we press on this button then the text value updates again so we have just accomplished our goal which was to update only this text widget when the counter changes and we have done this by using a consumer widget and once again this works by calling a builder every time the counter changes by the way here we are only using the counter value from the Builder arguments so if we want we can use an underscore as a placeholder for the context argument that we are now using and we are also not using the child argument so we can use a double underscore as a placeholder okay so it's now time to do a quick recap of everything that we have learned and I encourage you to follow this summary carefully because this really captures the essence of provider so we started off by reviewing the widget tree for the example counter application and we said that sometimes propagating state from one producer to one or more listeners is inefficient and requires a lot of boilerplate code and we have proposed provider as a possible solution to this problem and we have seen how to apply this to our counter example by defining a counter class that uses change notifier to notify its listeners when the counter value changes and then we have added changed notifier provider as a parent to the my home page widget and we have seen how to get the counter value by calling provider dot off with type counter with context and we observed that by default calling provider dot of registers the current widget as a listener causing all its descendants to rebuild when the counter changes and as an improvement we have passed a listen of false argument to our call in order to avoid a necessary rebuild and instead we have added a consumer of type counter as the parent of our text widget and with this setup this builder is called every time the counter changes and we can use this to rebuild our text widget with the updated value okay so I think we've come a long way and I could wrap up this video over here because our implementation works and is quite efficient as well however there is one more thing that I want to talk about you see in this tutorial we have chosen to implement a simple counter class which implements change notifier however if all we need to do is to hold a simple integer value and update listeners when these changes then we don't even need a custom class and instead we can use a value of notifier and as we will see value notifier and change notifier are very closely related so what I'm going to do is to quickly update our implementation to use value notifier and then we will take a quick look at how value notifier works under the hood ok so let's get back to our main file and first of all I can scroll up to the Declaration of the change notifier provider and here I can replace the counter type with value notifier of type int like this and I can also update the Builder argument to return a value notifier type int and I can pass 0 as the initial value to the constructor and then I can scroll down to the line where I get my counter and here I also want to update this to provider of value notifier of type int like this and I want to use this type in the consumer as well so over here I can replace counter with value notifier of int and finally I need to update the unpressed callback of the floating action button because this counter is now add value notifier and it doesn't have an increment method so what I can do is to delete this and replace it with a closure that calls counter docked value plus plus so that we can increment the value like this and this is all I need to do to make our counter example work with value notifier and just to prove that this all still works i can hot press start and when i press on the plus button i can see that everything works correctly and once again all i have done here is to replace all instances of the counter class with value notifier of int so this is a good time to look at how value notify is implemented and as we can see value notifier is a class that is generic on type T and it extends change notifier and the documentation says that value notifier is unchanged notifier that holds a single value and if we look at the implementation we can see that it declares a private value of type T and then it exposes that value with a guitar and it also has a Sutter which checks if the new value is equal to the previous value and if they are different then it updates the value and it calls notified listeners so this is a perfectly good replacement for the counter class that we had implemented ourselves and because value notifier is a subclass of change notifier then we can use it together we change notifier provider like we have done over here and the bottom line of all of this is that if you are considering to use change notifier just to store single values then you can use value notifier directly instead and this will save you some code okay so we have now reached the end of this tutorial and in this video we have seen how to use provider as a state management solution alongside change notifier or value notifier and all the concepts that we have covered are essential to understanding how provider works and they are also the foundation for more advanced flutter tutorials if you have enjoyed this video please like and subscribe so that you can improve your flutter skills thanks for watching and I'll see you on the next video where we will continue our deep dive about provider
Info
Channel: Andrea Bizzotto
Views: 68,965
Rating: undefined out of 5
Keywords: flutter, dart, android, ios, mobile app development, programming, tutorial, course, udemy, coding, provider, changeNotifier, ValueNotifier, state management
Id: MkFjtCov62g
Channel Id: undefined
Length: 17min 12sec (1032 seconds)
Published: Mon Oct 21 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.