Flutter StateNotifier + Riverpod Tutorial – Immutable State Management

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
river pot is not only about providing objects around the app it comes bundled and closely integrated with state notifier which is a state management class it resembles the default flutter's value notifier or even qubit from the block package without underlying streams this kind of immutable state management is just great for keeping unpleasant surprises at bay [Music] hello welcome to riso coder where you're getting prepared for real app development so that you will get freelance clients or a job and be confident about the apps you build so subscribe and hit the bell to join us on our quest for becoming in-demand flutter developers it's become quite of a habits over here on riso core to demonstrate different state management solutions by writing the very same simple weather forecast app and since the template by which we demonstrate different state management solutions is always the same you can nicely compare apples to apples because you know the end result is always the same so this tutorial will be no different we are going to demonstrate state notifier by building this kind of an app which you may have seen already in some of my other videos so basically we just input a city london search for it and it's going to output this simple weather forecast of some sorts and it can also perhaps output an error which in the finished app is actually going to show a snag bar at the bottom saying that some error occurred i do have a startup project ready for you so that you can follow along with this tutorial and not have to write all of the sort of unnecessary code which needs to be there in order for this app to function properly but it has nothing to do with state notifier or river path per se also this tutorial assumes that you understand at least the basics of working with riverpot so if you want to catch up on that you can check out the tutorial from the cart in the corner so if you want to get this code be sure to check out the written tutorial from the link in the video description where also apart from the startup project you can find all of the code written in this video links to the libraries and overall go through this lesson at your own pace so the star project which you can get from the written tutorial from the link in the description contains a weather model it consists of a city name and a temperature in celsius then we also have a weather repository which simply has one function called fetch weather which simply returns the weather model which is randomly generated the temperature is randomly generated and the city name well this comes from the inputted city name which is inputted by the user and then also we have preparation for the user interface which we will implement with state notifier as you can see here but we basically have all of the different states that the app can be in represented by these methods so build initial input will show this build loading will show the circular progress indicator then we have build column with data which will show the success for uh successfully gotten data right you should probably not write these kinds of widget returning functions inside of your own app but instead create widget classes but over here we are doing this for simplicity and as always you can go through this at your own pace from the written tutorial if you want to really take a close look at this so let's now go ahead and add the dependencies actually there will not be multiple dependencies but only one of them and that is flutter river part currently at version 0.12.1 so even though we are going to be using state notifier for state management we need to import only rear part here because river pod comes bundled and it's also very closely integrated with state nullifier and that's great river path is therefore a truly complete state management solution because it not only provides the mechanisms to provide things around your app such as provider the regular provider does but it also allows you to manage complex states so river pot as opposed to provider in my opinion is truly a fully fledged state management solution because it comes bundled with state notifier and it's also very closely integrated with it before going any further with our weather search app example let's briefly talk about the principles of state notifier shall we so i'm going to write a very brief example here over in main.dart state notifier is something like a flutter independent value notifier so let's demonstrate all of it on a class counter notifier for a brief demonstration so flutter has this default value notifier which needs to be provided a type which it then notifies about as you can see it comes directly from flutter and it's actually a specific sort of a change notifier as you can see and i'm sure you're all familiar with change amplifier at least so value notifier int right and you would have a counter notifier constructor you would call a super constructor and this needs to be passed the initial value for the value notifier and the initial value of our counter will be zero the count starts at zero and then we will have one void increment and over here we would say value plus plus to increment it now we can do this incrementation just because it's an integer this the value is an integer but if the value was something different you would say value equals and the new value in this case value plus one to be more verbose right so this is all possible with default flutter nothing special was used here everything comes from the flutter framework itself but state notifier is a bit better in the sense that it's independent of flutter you can use it also outside of flutter projects and it's also a bit quicker and a bit safer because the value which is called state by the way in state notifier is protected you cannot access it from outside of the class because over here for example if we instantiate a counter notifier we would be able to access the value and also set it like this right this is not cool we should not be able to set the value from outside that's actually quite bad and stay notifier prevents this see the value notifiers value is just totally public there is no way to prevent it being set from outside of the class so let's migrate to state notifier state notifier int we need to import flat river plot nothing changes except that the value is now called state so state plus one and also whenever we try to set the state value from outside of the class we get this squiggly line below saying that the member state can only be used within instance members of subclasses blah blah blah now this is only an info message at this point but as a good flutter developer you can always change the severity of an info message to for example be an error and if you want to learn how to do this you can check out the tutorial from the cart in the corner about linting in dart but the good thing is here that you are really protected from this kind of a silliness of a code when you set the state from outside of the class with stay notifier all right that's enough for the simple counter notifier example when also just so that you know if you have not used for example the value notifier previously whenever you set the state all of the listeners of the state notifier as you can see here are notified about the state change this is quite important so now we can move away from the simple counter notifier example and jump right into our weather forecast app over here having a single integer for a stages doesn't cut it so whenever a state is complex for example consisting of multiple subclasses or a freezed union you should write code for that state first and only then worry about the logic so we are going to do just that we are going to create the state classes which are going to represent the state of the app first and only then worry about the state notifier so let's create a new folder application that's how we categorize things around here because state notifier is by my terms which i have outlined in the domain driven design tutorial series a part of the application layer but that's not too important for this kind of a simple tutorial so we're going to create a file where notifier.dart this is where both the state notifier and the state classes are going to live so whether notifier and what kind of classes should we have here well we are going to be asynchronously loading a single resource which is the weather model and in such occasions it's quite simple to represent the state i'm just going to paste the classes in here so that i don't bore you but you can always get the code from the link in the video description from the written tutorial so at first we need to have the abstract class weather state from which each other of the classes is going to inherit and again you can also use freezed unions in your real life projects but here we are not using freeze because i do not want to bug you down with just another library you know in order to keep this focused on the state notifier itself then next is whether initial for displaying just the text input like this then yet another state is very loading it's again very simple it extends weather state and it has just a simple constant constructor and now we're getting into the interesting stuff which is weather loaded right this now has the weather model feel inside of it and it also overrides equality and lastly whether error for whenever a bad thing happens we get an exception we need to have a weather error class in order so that we can display the snag bar about the error so these are the states which we need in order to represent all of the possible states which the app can be in so again these are weather initial weather loading weather load bit and where error and now with these states fully modeled we can move over to implementing our stay notifier which is going to be called weather notifier so let's create a class weather notifier and it's going to extend state notifier which will operate on a weather state with this this is the abstract class now we will want to get the weather from the weather repository so we need to have a final repository field let's make it package private weather repository let's add it to the constructor now this constructor also needs to invoke the super constructor of the stay notifier subclass and just like we've seen before you need to pass in the initial state so obviously in this case it's going to be weather initial and then we're also going to have a method in here so it's going to be future void and you should always make sure that your methods return void in state notifiers because you don't want to return anything from the methods themselves you only want to update the state it's going to be called get better it's going to accept a string city name and it's going to be asynchronous because we need to do the fake network calls and let's at first say that state will be equal to weather loading so as soon as this method is called we want the app to show the circular progress indicator that's why we set the state to be loading right from the start then we want to actually load the weather so let's say await weather repository dot fetch weather and as in the city name we want to store the return value from this method called inside of a final weather and then once we have this weather successfully loaded we're going to set the state to be weather loaded and pass in the weather now in order to also output weather error we need to put this code inside a try catch statement because over here we need to catch the exception or actually only one exception so we can say on network exception which is a class coming from the starter project and whenever a network exception happens we can output the following state state is equal to error error and some nice message so let's say something like confederator is the device online with this we have just again implemented the weather notifier it will always update the state and ui will be able to react to these state changes but before we can start implementing the ui we first need to implement the providers so that we can actually get this weather notifier class into the ui and also to subscribe to the state changes from the ui so we're going to create a new file in the root of the lib folder called providers.dart and inside of it we need to first have a provider for the weather repository so let's create final where the repository provider is equal to provider where repository is the type and it will pass us a reference which we actually will not use here and we are going to instantiate a concrete instance of the weather repository abstract class which in this case is the fake weather repository so let's do just that fake weather repository will be instantiated and let's also import rear path here cool so this is the first provider the second one will be final where notifier provider and this one will be a state notifier provider this one is closely integrated with the state notifier which is nice to see it's going to pass us again the reference and this time we are actually going to use the reference because we want to instantiate a weather notifier which needs to get a weather repository passed into it and we can get the weather repository by calling ref dot watch and watch with a repository provider this one with these providers implemented we can now hop into the user interface so just like with every other rear part project we need to wrap the whole app inside a provider scope so let's grab the material app inside main.dart with provider scope and we're good to go now as you could see at the beginning of this video where i showcase you the finished app we have these methods which we need to call on certain states and to rebuild the ui whenever the state changes we are going to use the consumer widget which you are familiar with already from my previous tutorial about river pot so right here where we say implement with state notifier we are going to set the child to be a consumer and the builder will be a function which will watch the weather notifier provider but not this notifier in itself but actually something which is a field on this provider and that's a state or actually it's a property this state is an entire provider in itself as you can see the weather notifier provider which we have written ourselves is a state notifier provider but this state property which is present inside of it is a state notifier state provider this is very handy because this state notifier state provider which is automatically present inside any kind of a state notifier provider will automatically cause the ui to rebuild when you watch it whenever the state changes so that's awesome we're going to put the watched state into final state and now we're just going to check through all of the possible states and build the appropriate ui so i'm actually not going to bore you with this i'm just going to paste it from the written tutorial to which you can get from the link in the video description so let's import the weathernotifier.dart file and basically if stated initial we build initial input if state is loading we build loading if it's loaded we build column with data and pass in the state dot weather model and if the state is wetter error so else we build just the initial input but here is the thing whenever there is an error coming from the state notifier we want to show a snag bar but where can we put this code to show a snack bar well anything that should be run only once when the state is updated has just absolutely no place inside of any kind of a built method that's because the build method can run many many times over but we want to show only one snake bar in the precise moment when the state updates to error but when the state is already where error but for some reason the build method is run again we just do now want to show yet another snag bar and this doesn't apply only to snag bars but also to navigating and also any kind of side effects you may have inside of your ui code but if there wasn't enough also showing a snag bar inside of a build method will result in an error so basically we have no option then to find a different solution for showing a snag bar thankfully that kind of a solution is here and it's called a provider listener it's a widget and we are going to for example wrap the consumer with it so it's provide a listener and it accepts a provider and we are again going to specify whether notifier provider and again its state which is the state notifier state provider and it also has a on change method which passes us a context and the value which we are actually going to call state and now we can check if state is wherever we're going to show a snag bar so this is the simple usual code for showing a snag bar right here so just like that a snack bar will be shown by calling scaffold of context shows nag bar there is still one thing left here and we actually also have a to do all the way at the bottom and that is that we need to actually call the get weather method on the weather notifier whenever a city name is submitted from the ui so let's do just that as usual with river paths providers we are going to call context dot read and we want to read a weather notifier provider notify provider but this time we are not going to read the state but just the weather notifier provider itself that's kind of obvious because we are not interested in the state of the weather notifier we are interested in the notifier itself because we want to call get weather on it and pass in the city name from the ui now we can actually run the app and test it manually to see if it works properly and it seems it does so we can input a city my city course it's a let's see works then i don't know let's say london again and london could not be fetched so we got an error and also a snake bar was shown at the bottom as you can see and just for a third time the charm or how do you say it in english let's say warsaw and it works and just like that you have finished a real world app using the rear part plus state notifier combo for stain management it's effective immutable and clean so what more can you wish for now to go through this tutorial at your own pace once again and to also get all of the code check out the read tutorial available from the cart in the corner and if you are serious about becoming a great flower developer who can build real apps for clients or at a job go to flutter.education a link is also in the video description by the way to get the top curated flower news and resources aimed at improving your app development career over there you can also subscribe to my mailing list to get the best flutter resources delivered weekly right into your inbox and if you don't want to miss more tutorials like this be sure to subscribe to this channel and also join the notification squad by hitting the bell button to make sure you grow your flower skills because here on raisocoder i am determined to provide you with the best tutorials and resources so that you will become an in-demand flutter developer if this video helped you with understanding the river pod and stay notifier combo give it a like and also share with other developers who are surely going to find this state management solution beneficial too leave a comment if you have anything to say and see you in the next video [Music] you
Info
Channel: Reso Coder
Views: 19,031
Rating: undefined out of 5
Keywords: resocoder, tutorial, programming, code, programming tutorial, flutter, flutter tutorial, flutter riverpod, flutter riverpod tutorial, flutter riverpod example, riverpod vs provider, flutter provider tutorial, flutter provider state management, flutter provider architecture, flutter service provider, flutter service locator, flutter getit, flutter getit provider, flutter state management, riverpod state management, riverpod stream, flutter state notifier, flutter cubit
Id: 3OdciTLjSNA
Channel Id: undefined
Length: 27min 7sec (1627 seconds)
Published: Fri Dec 11 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.