ChangeNotifiers and Provider - Live Coding with Flutter

Tensor Programming · Intermediate ·📐 ML Fundamentals ·7y ago

Key Takeaways

The video demonstrates the use of Provider and ChangeNotifiers for state management in Flutter, along with Built Value for immutable data collections and JSON serialization, while consuming the Hacker News API. It also showcases the use of MultiProvider, ChangeNotifierProvider, and StreamBuilder for handling streams and managing state.

Full Transcript

hey guys welcome to the livestream I see that there are already quite a few of you in the chat so I'm just gonna wait for my analytics to update see how many there are and then we'll get started here so how you guys all doing today or this evening and it seems a lot of you are watching fairly late at night you that's not too bad Rodrigo got from depay he's watching at 1:30 or 12:30 1:00 and then Martin's watching it 10:30 already so let's see since here I've got one concurrent year but I don't really believe that is provided the best pattern for flutter dead provider is not really a pattern as you will see it's a part of a pattern and what makes provider interesting at least is that it's very easy for you to get into so I'd say for a beginner developer the easiest thing to use would be the state management that I'm in a show today got some people from Zimbabwe and Ghana right on guys glad to have you here and it looks like we've got 16 people in here so might as well start now let me just pop this chat out so that I can keep an eye on it alright ok so let's go to the browser and I'll show you what what we're doing today so we're going to be using the provider as stated in the title and provider if you guys have seen any of my blog tutorials we've implemented providers by hand but we've never actually used the provider library specifically in a tutorial the implementation that I did in some of my last few tutorials is literally just a slimmed down version of what provider offers and so for the longest time I just like kind of refused to even look at the library even though everybody kept telling me how they're great things about this library and then finally after watching IO 2019 I came back and I took a look at the library and I was like yeah yeah you guys are right there's a lot more to this library than what there was before so provider really is just a way of taking some kind of state and it can really be a block or it can be just a normal object or a change notify or a stream it can be a value just anything that you want to keep track of and you can just bolt it to an inherited widget and then access it anywhere in your widget tree and so it's very powerful in that way so along with provider we're also going to be using built value and built collection and I should really pull those up hang on if I can spell so built value uses the Builder pattern book value uses the Builder pattern it gives us a mutable data types he gives us JSON serialization and a bunch of other great stuff and we'll be using that to make an application that consumes the hacker news API so this hacker news API it's got a few items in it that are interesting and I figured might as well I'll use it I'll show you guys how we could do something that's fully featured with provider and with built valuing and the change notify your object as you guys will see so I've never actually used this API so I I just know the basic stuff that's in this document here after looking over it for maybe like ten minutes so this will be interesting to say the least get back into the code any of you guys got any questions that's far what you will see today is 100% usable for a real-world project yes that being said keep in mind this is all live coded which means that of course it's not going to be the most optimized code in the world and yeah I'm gonna be rushing a bit because I want to get as much stuff done within an hour and a half to two hours so you know if if you just take the code as it is you could probably improve upon it and then ship it in a production level application all right so our basic app you know of course we've got our two stateless widgets material app and the scaffold I also went ahead and I added a bottom navigation bar about a map bar just by default because I think we'll use one and I've pulled in our dependencies so I've pulled in provider HTTP because we need to grab from the API I pulled in your own launcher because I want to be able to have us serve out to like a browsers or like if you want to see one of the articles then you just click a link and then it would send you over there and so your launcher is the best way to do that and then of course we've got build value and built a collection and to make these to work we need build a runner and built value generator and these will be in our dev dependencies all right so before we actually get into all of the json serialization and the data and all that stuff i want to just show you guys a very simple example of using provider to change the theme of our application so we're just going to create a button in here and we'll make it so that we can click the button and have it change from one theme to another and then back again so for this to work we need to inject the provider the the data up at the top of our application so we want to inject it in the very root of our application and we also want to set up the actual data object so let's do that first I'll create a folder here called state and then inside of it I'm going to create a file called theme state theme data theme state dirt and we'll create a class and we're going to need to import flutter material because we're going to need a object called the change notifier so our class will be theme state with changed notifier and so we're using change notifier as a mixin change notifier if you actually take a look at it and it's really just a listenable and what this essentially means for you or for anybody using it is that you can add listeners in the widget tree so you can make it so that any of your widgets can watch this object and then if the object changes if some of the state changes you can go ahead and call where is it here it is notify listeners to basically alert them that you've changed and then they will rebuild so it's in a way it's a bit like using what's it called scoped model it's like scoped model but it's built directly into the flutter framework and so I'd really like in this entire state management method to scoped model version two and in fact I think they even said that in the Google i/o because it's it's is really similar so first I'll create a theme data here I'm going to call this the dark theme so just dark hacker and news theme and we'll just use the theme data dark preset and then we'll create another one here and this will be the actual hacker news theme and this will be custom for now I think what I'll do is I'll just use theme data right just to show you guys this but as we get further into the app will actually go and get the colors for hacker news using a color picker alright so then we want to set up the actual theme data item that we want to watch in this object so this will be the theme data that we're setting up and we'll also have a boolean here called is dark to let us decide whether or not our theme is the dark version or the right version and then we can have our theme States constructor and in the constructor I just want to take the theme data and set it to by default the Packer native scheme like that then we can have a we can make a getter so I could say well let me just do it like this I'll just do a normal function so this will go and get our theme data and then we'll have a set theme function and I don't want to make a setter because I don't want to really pass anything into it I'll just check to see if it isn't dark or if is dark is false if it's false then we'll take the theme data and we'll set it into the dark Pecor news theme and then otherwise we'll take it and we'll set it to the peccary News theme like that and then down here we'll take is dark and we'll invert it so if it's true we'll turn it to false and if it's false will turn it to true and then of course because we want everything to know that we've changed our state we need to call them notify listeners here and so that will basically tell the app that we've changed the theme and so it should rebuild all of the Associated witches right so that's that's good that should be enough for this so let's go ahead and import this in our main application so just grab it real quick if I can spell properly there we go and we're also going to need provider real quick so and so what I'll do here is on our material app I'm going to wrap this in a provider and actually not a provider but a a a change notifier provider so this is just a a version of the provider that's specifically made for change notifier so we put in the change notify provider and then we need to put in a parameterised literal of the type that we're passing in here so the data structure which is just our theme state object like that and then for the provider we have this builder function so the builder function and you can also optionally put in a widget for the child of the provider if you want to excuse me just make sure I've got all this correct and it looks to be alright to me I think we may run into an issue here though yeah we're gonna run into an issue here so what I'm what I want to do is just take the um now you know mmm yeah you know I actually want to make another widget here and I'll explain why I'm doing this I'm just gonna call this the route and let's and actually why don't I just use the little thing so call this route and the main reason why I'm doing this I'm just gonna hoist our change in notify our provider up into another widget like this and then call to my app directly from here and then a more put route in here and the main reason why I'm doing this is because of the build context if we do it this way then the build context will not have the appropriate data inside of it and it will make it very hard for us to change the theme data so up here we can put in our I'm puttin our change notifier provider and we're going to just create the Builder so builder takes in the build context so it's just context and then we want it to build out the object here and let me put this data in here it's a theme data theme state and we just want to take and build our themes stay like this and then our child here will be the my app widget all right so now we've got our theme state object injected above the tree above this material app call and then we can get it anywhere in our tree that's below the material app call so I can come down here and now and I can say final theme data equals provider of passing the context and we explicitly want to get a theme state so to do that we need to pass in the parameterised type and by doing that it basically tells it okay go search in the tree for the closest theme state data object and then grab it for us and then put it into this variable and so we can then use that and put it directly in a theme here now so theme data dot get theme and then that will get the theme for us and then down here let's grab this and we'll use it again down here in the scaffold we can go ahead and run this again and we'll create a button inside of the app bar let's put a title here I'm just going to call this the hacker news app and then in the app bar I'm going to create a an actions icon so icon button do we have something yeah there we go use this color lens it's like a little palette and then on pressed on this button we can call theme dataset theme and then that will change the theme for our entire wrap let me go ahead and now run this in the emulator and we can actually see all this in action okay let's see you Oh nagawa yes it is similar to the genie writer that I made a few months ago it's just got more features attached to it so that's what makes it much more powerful in a way for instance the provider will automatically dispose of any resources that you don't need anymore and so it's it's pretty pretty useful let's see not usual in the weekday live-streaming I actually believe it or not most of my live streams have been during the weekday but I just thought recently as the summer approaches I'm going to try and do more scheduled weekly livestream so I'm going to try and do something that's pretty regular so that you guys won't have to guess when I'm going to be streaming um let's see will you do a video about Scala yeah I've been wanting to do Scala for a long time I'm just not sure what the what the interest in Scala is these days I quite like Scala I find it to be basically the Haskell of the JVM and yeah I'd really love to do some stuff with it Khalid says is it yeah Khalid maybe I'm saying that wrong he says he used scope model in one of his apps should it drop it and shift a provider well if you make scoped amount of work well then you can you can obviously use it it's it's still a solid way of managing state you can use it with provider or you can if you want to just remove the scoped model and replace it with a change notifier and then use provider like I'm doing here you all right so we've got our app open you can see here it's it's got a nice well normal theme click the button here and it changes to dark stream builder is not the most I mean it's optimized if you have a stream it it really depends on what you're building and the thing is the it's funny one of the things that you don't really get if you if you don't really look into it too much so a lot of the builder functions in flutter are stateful widgets and so behind the scenes they call set State inside of them for you and so you're just taking a stream putting it in there and the stream builders like okay well I know how to handle the stream when I get an event I'll call set state rebuild the app from this point down the widget tree and so you know that it can be useful if you're working with streams but if you're just working with classes or if you're working with futures maybe you want to use a future builder or you know maybe you want to use a provider or like we're doing here you know it just really depends on the use case so yeah we've got our theme work in here and that's pretty nice all right so let's now build the actual logic to go ahead and consume hacker News's API so I'm gonna go ahead here and create a folder we'll call this models and inside of it will create two files first one will be called let's just call this stories and this will be our our main serialization model for all of our hacker news stuff and so we need to import we're going to need dark convert I'm going to need built value and built collection and just normal dope value we're going to need probably the built value serializer and well to define this as part of the generated file which will be called stories G Dart based off of the file name that we just created and while we're at it let's create another file in here called serializers dart and i will reference that as well so import serializers pretty sure it well see this will be serial there we go all right so now we want to create an abstract class and I'm going to call this class stories and we're going to implement built and built inside of it we'll have our stories and then a class called stories builder which will get generated all right so if we go and take a look at the API let me go back over there there are a bunch of fields that we want so here they all are we have the ID we have a deleted feel we have type this by field time text dead parent Paul and you guys get the point this is what the Jason sort of looks like so this is interesting when you go and you go to the the main pipelines for hacker news you literally just get a list of these IDs so it'll look something like this so if I go and get like the top stories on Hacker News I'll just get a list of IDs and then we want to use those lists of IDs to go and get each individual article by calling to the ID name as you can see here it says item and then it has an ID name and dot JSON and if we open that up you can see there's actually a JSON structure for that specific ID so we want to pull in all of our IDs and then we want to serialize each one into a dart object so we can use all of these fields to then or we want to implement all these fields in our stories object so let's go ahead and do that so first we start with the ID and this will just be a getter for it then we'll have a nullable value which will be our boolean called deleted and then we'll have a string which would become type another nullable which will be bi so the author there's a an inch for the time and we're going to be using this nullable in our tation quite a bit here there's one called dead which is a boolean type then there is a integer called parent and this should be nullable as well let's see then there is a pole which will be again nullable it's an integer and then we have our most important piece which is the built list and of type int and this will be called kids so these were these are all of the child posts for whatever it is that we're currently reading then we have another string here called URL wait did I flip back over no I didn't all right sorry about that guys so starting here doing all the data so we have the ID that deleted the type by time dead parent poll then this built list of kids string of URL and this should be null about two then we have an int title let's see then we have another built list called parts and this is a bit list of int and then we have an int called descendants let's make sure I spell that properly and yeah now I think that's all of them so these are all the fields for our JSON that we're going to serialize and so now we need to set up a little constructor here so stories and this will be a private constructor like this then we need to set up a factory constructor those stories the factory constructor takes in a function called updates and we pass in the threes builder object I'll call it B and then this is going to output a a class called stories with a underscore and dollar sign in front of it and that will be our generated class and then because we want to serialize this with JSON we can make a static it's utilizer and and actually this is not going to work until we actually implement the serializer class let's just cut that out for now all right so I'm gonna go ahead and run the terminal command to actually generate this and I guess I'll do it right here on vias code believe I've got it in here so flutter pub run build runner watch this should watch for all the files and then build the ones that we need generated so we'll use this to generate the file we need for our stories and then we'll build our serializer and do the same with it so let's first get this build it may lock up because I'm running flutter in the background but I don't think it should it should be alright now let's see you so I'm not gonna try to say your name but he says I think a scholar burial may be so interesting as Kotlin what do you think about Ruby I think Ruby is a language that is more or less past its prime unless they do some really impressive things with the compiler I don't really see a reason to use it it's got a great developer experience mind you and Rails is a very nice framework still worth learning but Ruby on its own just doesn't blow my hair back I'd prefer to use elixir frankly so so sucky Hideo says that currently on the flutter boring show they did make a hacker news app III didn't know that I don't really watch that's I think I've seen a few of their episodes and of course I people were commenting because I didn't have the IDE on the screen yeah yeah you want me I wasn't losing frames the problem was I just forgot to flip it back sorry about that all righty so looks like we've got our generated file so let's take a look at it so we've got our stories object which is the one that we want and it's got all of our items inside of it and then it's got the factory constructor then a bunch of other stuff too so yeah this is all a bunch of code that we really didn't want to write and so built value did it for us makes it so that this class is easily consumed from JSON and is immutable which is great all right so let's set up serializers and in fact to make this quicker just gonna go and copy some of these let's grab a few of these just paste them in here we're going to need built collection let's see I don't think we need built value itself but we do need the standard json plugin like that and we also need the serializer which I think we've got yeah gather right here and then we're also going to need of course our stories file now this will be a part of serializers G dirt much like our stories file was and in here we want to set up serializers for and we'll put in our class here as a constant the class called stories then we'll just say serializer serializers equals underscore dollar sign serializers this will be generated for us make sure I'm spelling this properly see réaliser looks to be right then we want to set up the portion that will allow us to deal with the json plugin so serializers dot - builder ad plugin and this will be standard JSON plugin there we go so that should go ahead and generate it for us and actually did it pretty quickly looks like we didn't get an error so yeah it's pretty basic here but this code allows us to use the Builder pattern and serialize our data and so yeah we have no errors so this is good I wonder why I guess we don't actually need built collection in here and I guess we won't need dart converting this one let's see for this though we do want to add one more thing so I want to create a function that will make it easy for us to parse a story from JSON and then return it as the object so I will just call this parse stories you know taking a string which will be a JSON string and then let's say final parsed equals JSON decode by the way so JSON decode this function here is basically just JSON decode like that exactly the same thing except of course if you want to have a variable called JSON this can be a bit of a pain so you can just write it like this and it's it's easier to deal with so we'll put our JSON string in here and then we want to say stories stories evils and we want to call to our standard serializers we want to deserialize our data and so we want to put in stories dot utilizer and then the parsed data that we just got let me make sure I'm spelling that properly yeah looks like there's an error but we'll figure that out and then we'll return our stories so let's see what's the issue here so okay oh right I'm using the wrong function this should be deserialized with and should be Collin see realizer I probably spelled it wrong didn't I now I think it's because I called it serializers you all right I didn't make this cereal I for Jesus I forgot to make it because remember I needed to make the serializer file so Eliezer stories get serializer and then this will just point towards Marie's serializers like that and now this should work let's see do we have an error going on here okay so this is going to need our built collection now so we needed to actually bring that in I knew we needed it I just apparently spaced out on that and there we go so that it takes care of all of our errors does anyone have any questions thus far there will be a recorded video after the stream ends so I always just put them up on edited afterwards this is a real-world app neat it goes in it consumes an API I mean all the apps that I build are something that you could use in the real world like you want an online pizza shop with a complete back-end yeah I mean that's great and all but it's a real pain in the butt to write an API when all I want to do is or I'm not all I want to do but all I want to do is explain the parts of flutter you know it's easier to use a fake API the consuming of the API and the writing of the API is not the difficult part in my opinion anyway I won't get into that at some point you know there will be a point where I'll do another polyglot tutorial probably build something like an API with rust and then consume it with flutter in some way what about the tools section what's going on with the tool section you [Applause] I don't I mean everything that I've written if should be alright I don't really need to check that out alright alright so let's move on now so we've got our data classes all set up we got our serializers and we got some helper functions so this should be all good let's now set up the state file so I'm just gonna call this app state and in here we'll have basically all this state that we're going to need to read from hacker news and then go and use those IDs to go and actually fetch the individual articles and we're also I guess will create like a cache here so we can create like a hash map which would be a bit of a cache we're going to need dark collection dark invert probably going to need foundation we're going to need HTTP then I'm going to alias this as HTTP and of course we'll need our model so the story's model and that stores the dirt and I think that should be enough so now let's create an enumeration and call this the story type and we're specifically going to get the top stories and the new stories so top stories let's just call it top story and then new story find actually might as well make these stories rather than the story so on unhak er news there are a bunch of different types I think there are like job stories of our job articles and and and a bunch of other ones too we're only specifically going for top and news because why not I don't really feel like extending it out to get all the different types right so I'm actually going to shut this down too because we don't need this running in the background now that it's already built so I'll close that now let's make our apps state class and again we'll have it with the change notifier so we'll use change notifier is a mixin so that we can access the notify listeners functions and pass it around as a change notify our listener in here we want to set up a bunch of lists so we'll have top story IDs and we'll have new story IDs so these will be the IDs for the top stories and the news stories respectively and then we'll have a list of stories which will be the actual top stories so this will be all of our top story objects and then we'll have another one for news stories and let me see perhaps I should just get the terminal emulator off the screen so it doesn't get in the way let me fix the chat real quick you don't value do serializing for JSON but is it really different than doing it manually by listing variable as you listed on the model and then method yes it is different it gives you a mutable or it gives you fully immutable data and it uses the Builder method it's also much easier to do for it's much easier to reason about when you're working with more complicated JSON structures and yeah there are a bunch of different advantages I highly recommend you go and actually read the documentation I'm granted you could go and build your own you know JSON data structures and your own to and from JSON data structures but the more fields that you have to serialize or deserialize the more of a pain in the butt that's going to become so that's all I can really say for now all right there we go fix the chat okay so where were we all right I want to have a cache so call this cache and more just use a hash map this would be a hash map we're gonna store all of the stories by their IDs so it'll be IDs and then stories and this is is it stores yes stories so each story will be ID and stories and then I probably should have called its story but whatever then let's have the URL for our for the API so base URL it's just HTTP hacker news and actually let me go grab it it's a firebase URL so there it is just hecka news that firebase tayo or Hecker news that firebase io dot-com backslash version 0 backslash that's our base URL then we're going to use it to build all of the other URLs so we want that in a variable let's see we'll have to boyens in here one called top is loading set this to true by default another one called new is loading so we'll have internally a way of keeping track of whether or not we've loaded the top stories are the news stories and we want them to be separate because we'll have them on separate pages and then we'll have our story type which will just keep in here we'll set this to by default story type news stories that way when we open the app it goes and gets the new stories by default alright so now let's create a constructor and I don't know why I added the brackets because we don't need them right now and then we're going to need to put this inside of a factory constructor this just will return appstate like this and the main reason why I'm doing this is because I want to kind of maintain a bit of a singleton pattern here so that we don't over make these objects and then this should be alright it's not a complete singleton pattern we're not like maintaining it and statically inside of this object but should keep things pretty pretty clean okay so now let's create a function to actually go and get the IDS for our stories based on the story type so if we pass in story type news stories then we want to go to our base URL and the base URL plus it'll be backslash new backslash stories dot JSON that's what we're looking for and then if we're looking for the top stories it'll be backslash top backslash story so JSON so we'll call this it'll be a future pass back a list and caught in it stories passing our story type have it be asynchronous and what we can do here is just create a string for the front of the URL and we can use a ternary operator to determine whether or not our type is Story type news story if it is we'll attach the I will pass back the new string and if it's no then we can pass back the top string and then we can build our URL by using string interpolation so our base URL and then we'll put our front ERL in here and then we'll attach this to and actually you should probably wrap this in brackets and then we'll just attach stories do something like that let me see if I can actually show you guys what this looks like so let me grab this top and got a permit tonight hang on and that would suck if I can't access the data all right that's why I don't need the backslash there we go so let me show you guys this browser so you can see here when I call to you say top stories that ji-sun we get a bunch of different stories here I think there's like 500 of them it looks like yeah 500 of them these are all just IDs and then we can use each of these IDs to go and get the attributes for each of the stories so we want to call to either top stories or and if I put in news or new rather and we have another 500 IDs so the latest 500 stories and all of their IDs so our res it goes away HPP gets passing our URL so that I'll go and get the response and then we can just return the JSON decode res that body and actually let's add some error handling so if res status code is not equal to 200 meaning our response failed and we'll just throw couldn't catch stories you what's going on what's happening in the chat oh there is a web tool where you can feed a piece of JSON and then it will generate the basic build data code for you there whatever I'd rather do it manually anyway it's not a big piece of JSON but I appreciate you trying to get me to look at it maybe next time I do want to do our unofficial tutorial on build value for now I'm just using it incidentally in this project that's why I'm not really going into much depth on what it actually does but yeah you're right it is another step in the terminal you anyway yeah guys don't worry about it don't fight over it it's it's not that big of a deal then both are pretty good tools like with everything with dart all the tolling is really great so and it's always changing so it's nice that you know about it if you're ever using built value then definitely use it alright okay where were we alright so we have our ended stories now I guess we can create a function that actually goes and takes the the IDs and then updates the stories so actually before that oh no no let's do this so future stories call this get story and this can be private and pass in and ie make it a sink and we want to attach our cash in here so we'll check to see if the cache contains the key of the ID inside of it or if it doesn't rather and if it does and then we'll say final URL equals base URL item backslash tidied JSON so this will actually go down and get the JSON for the ID that we're looking at this will go and get the URL for the idea that we're looking at and then you can go and get the response by saying final resi goes away HTTP got yet press it in the URL and again we could do this a little check here with the if check see if our status code is 2200 or not and we could say could not fetch ID story like that and let me actually get rid of these curly brackets you don't really need them because these are single line and what I'd like an else clause here and if it works and we just want to say cache of ID equals and we want to call to our parse stories function that we created in our stories dart file and we'll pass in our res dot body so that it actually create the proper object for us and then outside of this if statement we can just return cash tidy like that so this will actually return this story and regardless of whether or not we actually went and got it with the web so in this way we have a hashmap this is in the background and it maintains all of our stories and then as we get stories we can add to it and do different things with it which is kind of nice [Applause] I'd sell now we want to pull all this together and basically use get story and are in histories functions to update the lists that we have in here so this will be a future null it could be a future void - it doesn't matter just call this update stories this will take in the story type will be asynchronous and will have a boolean here Clark fetch set this to false by default then we want to run a big if check so if type equals story type got news stories and our new stories is empty or and I can just copy this part here change this from new stories to top stories and this part to top stories so we're on to check to see what the type is and then we also want to check to see whether or not the the lists are empty and if they are if these get satisfied then we want to just set our fetch true and this is a bit of a Messier hang on so a little bit better kind of wish it would format down whatever so yeah this was that fetch to true and then we can come down here and say if fetch so fetch is true then we want to go and get our stories using our initialize function so if the story ideas story I DS equals a wait initialize or is it in it stories passing the type and let's use the ternary operator type it's very tight new stories new story IDs we can use this to put our story IDs into our new story IDs and if the type is not new story IDs and we want to put it in our top story I use that way we have them all organized in either one or the other list and see if we can get this to format better and yeah there should be like that all right so now we want to iterate through all these and we could use a map function but the problem is that we've got 200 different stories that we want to we have 200 difference to our 500 different stories rather that we can read from the API and that's just going to take forever to load so we'll use a for loop and then we'll break and like index 15 so that we only get 15 of the news stories and 15 of the top stories so you can say for VAR ID and storing IDs I really don't like using for loops but whatever you can't break out of a for each statement or a map statement so then we just say stories news story equals a rates get data passing our D and is a get data or gets story gets story so that goes and it gets the story for us and then we need to pass it into the appropriate list so we can use this format again so if our type is new stories and we want to take our new stories list and add all of the new story less that we're getting back this new story here you or not at all but just each one to our list and we can do the same for the top stories you like that then we'll have an if check if story IDs index of ID its greater than let's say - we'll call notify listeners so will actually update our data every two stories that get read into a list and then we can have another if check here if story ideas dot index of ID it's greater than 12 or you need to set 15 right we'll break out of the loop so we only get the first 15 stories from each type let me read it then outside of our for loop we want to update our is loading fields and again we can use this ternary operator for this so I just grabbed that piece so if type is equal to new story and we'll say new is loading equals false otherwise we'll say top is loading equals false like that and finally we want to notify the listeners that all the state has changed and so they will pop up in our user interface already so this is most of the this would be most of the actual logic that we need we do need to create some getters real quick though [Applause] so let me I'm up here this makes them getter so I'm gonna say and actually the other thing I want to do is call to update our stories inside of our constructor so as soon as we build this object it will go in [Music] call to you this function here you so we just say updates is pass in our story type and then that's it it should be alright let's create our getters and setters I think we only really need getters so we need to get her for the list of stories which will just be called stories and this getter will just check this story type to have story type equals story type names stories and we want to return our new stories list else will return our stories list so when we get the stories it'll be context sensitive based on the page that we're looking at and then I will do the same for a getter for is loading so let's just grab these and his loading will return new is loading or top is loading depending on the context oh yes and we also want a getter which will get all of our stories so all of them combined so this stories get all stories and we'll say this please all stories equals set this up rather initialize it and then we can just call all all stories at all add in our new stories and then add in our top stories like that and then return our list of stories through this getter right so that should be alright and oh I think there's one more thing that we're missing and it's because our application it's going to use a bottom navigation bar we do want to have index in here so this will be an int this will be the index of the actual page that we're on so we'll have 0 m1 and I'll just call this bottom index set this equal to 0 by default and let's create a getter for it as well simple getter this time let's get bottom index like that and we also need to create a function that will specifically call to update stories with the different types so let's make that real quick so this will be based on the index that we're looking at so all those change story type passing an index or int of index rather we're just going to say index is zero and the story type is going to be story type news stories and then the bottom index will be zero and we'll say else take these two and change it to top stories and bottom index of one then we'll call update stories with the type inside of them and the type will be our story type and then we'll call notify notice by listeners to actually tell it that we've updated our state and I think that should quite do it for this and maybe missing something but we'll figure that out when we actually get into the UI does anybody have any questions thus far everybody got pretty quiet while I was doing all that because that makes sense we'll wire this up and then we'll go back over and talk about how it's working and all that stuff so that you guys can really get an idea of what's going on yeah it's a pretty big class but you know what it's fine the way it's set up it's it's actually just basically the state for our entire app if I was going to make this app bigger I'd probably start splitting it into pieces but because this app is relatively small it's not too bad all right so we have our change notify provider what we can do here is have another one so just chain them together but that's really just really kind of annoying to do so instead provider gives us a object called or a widget called a multi provider and we can use the multi provider to just pass in a list of providers so instead of let's see I'm just going to replace this with new multi provider and we don't need to specify the type and it doesn't have a builder either Multi purveyed er does have a providers field and this is a list of providers that get injected at this portion of the widget tree so we want to inject our theme state and then our app state right here and speaking of which we need to import the app state so first we'll inject the change notifier provider of theme state type and there's a little named constructor here called value and value will allow us to then specify the notifier which will just be our theme state object and so this is basically like what we were doing before except the only real difference is that we're layering these inside of this multi provider so then we'll have another change notify our provider if I can spell of our app state and again we'll use the dot value and then this notifier will just take in the app state object like that so now both of these are injected at the very root of our widget tree and then we can access them anywhere and though by the way we just got an error so we'll figure it out what's going on here while we're looking at this let's see it's saying - sentence zero IDE score time blah blah blah stories failed to do - deserializing Mac OS depreciated scripts ba-ba-ba-ba-ba and failed due to type string it's not a subtype of int so it looks like maybe we have an incorrect subtype for one of our fields so let me find out which field let's see so it's coming from there from there let's see maybe this maybe if this is a bear instead of an INT it'll clean it up all right no no this seems to be something else entirely let's see you know reload this thing and actually it seems like nope there's the error again okay it's fine so it seems like our stories is just the the actual set up is perhaps wrong one of the ends might be supposed to be a string instead so let's go through this real quick you geez all right so ID is an integer obviously let me see let me pull up the API here so ID is an integer an integer then we have deleted which is boolean string type is an integer or is a string rather by is a string time is a unix time should be an integer an integer booyah dad is a boolean parent is an integer Commons parent either the common of the relevant story let's see parent is just an ID so it's an int Paul let's see this should just be an ID as well I'm pretty sure let's see perhaps this is the problem let me see Paulie is an integer so no it's not the problem then we ever built a list of integers which is our kids and that should be an integer of course it's just the IDS of the items comments then there's the URL which is a string is the URL of the story then the the title is not an inch that's what the problem is title is a strength I don't know why I put an int for title alright that was pretty obvious let me just well this is already still running apparently I probably have to restart this thing using hi restart should not crash let's see okay yes I need to actually completely restart this thing now because the problem is the generalized code changed it from a into a string and yeah that's that's an issue let's just make sure that it actually built it properly title all yeah so this is now a string and if we rerun our application oh yes and of course you guys probably couldn't see all the crashing that was happening in the terminal or the emulator because I had it shut down but it doesn't really matter I just had a bunch of red pop-ups as you would expect with a flutter [Music] fix the chat again I don't know why it doesn't scroll in and out on its own sometimes it should yeah you're right in retrospect if I'd used the web JSON tool this would have been much easier but I didn't so whatever it's not a big deal you know I'm so used to writing these manually that it's alright I mean I knew that this was the error but it could have been something else as well so that's why I wasn't that worried about it now this is what I was worried about before the the actual watch function is now blocking flutter from executing there from launching launching the application so sometimes you need to go ahead and close that down before you can get flutter to to actually launch anything alright while we're doing this I actually want to go ahead and get the theme data for hacker news so let's let's go over to hacker news and take a look at this thing it's really not that interesting the actual theme it's just an orange color and then like a gray color let me show you guys uh yeah he missed you missed most of the data stuff but if you watch the video later you should be alright let me go over to the browser so this is what hacker news looks like I want to get this little icon and we also want to get the color I don't have the color picker on Mozilla but I do have it on Chrome and so I'll grab the colors from the Chrome unfortunately I can't show you guys Chrome because as long as I'm using hardware acceleration it doesn't work in OBS which is kind of a pain alright so let's go into our theme state and we're going to be setting up the this here the hacker News theme so this will just be a normal theme data let me make sure that you're actually looking at the editor again so I've changed this to a theme data from theme data light and the primary color is this that like sort of sandy color that you saw before that is I'm gonna actually get it right now so should be color this is what the hex looks like so it would look like this to change the hex into the appropriate binary format that we want you put in 0 X F F F F for the Alpha and then you just take this portion of the hex and just paste it in there and then that will create your color for you it's actually fairly easy so that's our primary color and I need this orange color the orange color let's see stupid color picker keeps pulling the wrong orange okay I'll put this as the accent color so 0xff and then the color is FF 6600 that's the orange color and actually I want this to be the background of the canvas color so this will be like of the little highlighted features and then the accent color will make it a orange color like this but we'll make it a darker color so just use the color picker to change this sorry you guys can't see all this so I've just I selected the orange color and then I'll just take it and make it darker so the color here that we'll use is 8 4 3 C 0 B and then we'll have a scaffold background color and make this X 0 F F F F F 6 F 6 e F and then we'll say with opacity 0.6 so this will make it a kind of gray color alright so there we go that's that's what it kind of looks like let me make sure the hot restart in yeah fun awesome flutter does have the heck of news like I'm a time I'm just pour it in from the web it takes two seconds so you just grab the URL for this that's just news web combinator why 18 gif and that's literally audience and actually there's a better icon let me saw a better icon earlier when I was researching okay so right this one here I just like just follow this over to the page it's on and then he's the inspector to get it so it's just this webpage H and Al Gore comm assets logo like that I start we just copy this and then we can use it in our app state so let me just put it in here and then comment it out so let's flip back over so I'll just put it in here comment and then we'll put it in our app bar all right so looks like the theme is working we won't really know until our bottom navigation bar pops up but yeah this should be black then we should have like white text in the body and then when we click it it should turn orange let's see let's see if I add like some text here all right so that's just great text for now but it should should change orange when we actually have the bottom navigation bar let's change this to a bottom our navigation bar anyway and by default I think it needs the the items and the stuff like that see I'll go back to a bottom at bar for now because we're gonna be building out other parts of the app so let's see let's go and build out our app bar and what we're also going to do is build out it was called a search delegate which will allow us to search through the data that we have and I'll show you how this works let me actually get to it kind of a cool little feature and if you know how to do it is it's actually pretty cool allows you to basically add searching to your application in a very easy way alright I'm also thinking that I should perhaps take this we split the material app and the thing all right so this should be alright I was thinking that we might run into a problem because sometimes if you're trying to call to the navigator from the widget that has the material a pin in it it doesn't actually find it properly because the context doesn't find it until after it's been built it's kind of a strange issue but I think we've kind of dodged a bullet here I'm glad with regards to that so in the app bar we just want to take and add a leading widget to this and the leading widget will have our have the icon that we just brought in and we're also put a circular progress indicator up there and you know that will change based on the is loading getter that we created so we can say provider pass in our app state because we're looking for the app state object and we're looking for is loading so we use the ternary operator and we'll have a container and then another con

Original Description

#flutter #tensorprogramming #provider In this Live Stream, we will build an application using ChangeNotifiers and the Provider library to manage the state. We will also be looking at Built_Value as a means to create immutable data collections. Feedback is welcome Source Code for this example: https://github.com/tensor-programming/flutter_livestream_provider Request Form: https://goo.gl/forms/rFjHcZMRJ3bYPEC03 Feel free to support the channel: Patreon: https://www.patreon.com/tensor_programming Check out our Twitter: https://twitter.com/TensorProgram Check out our Facebook: https://www.facebook.com/Tensor-Programming-1197847143611799/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tensor Programming · Tensor Programming · 0 of 60

← Previous Next →
1 NodeJs, Text editors and IDEs
NodeJs, Text editors and IDEs
Tensor Programming
2 Vanilla JS todo App
Vanilla JS todo App
Tensor Programming
3 Elm Tutorial part 1
Elm Tutorial part 1
Tensor Programming
4 Elm Lang Tutorial, Part 2
Elm Lang Tutorial, Part 2
Tensor Programming
5 Elm Tutorial Part 3
Elm Tutorial Part 3
Tensor Programming
6 Elm Tutorial Part 4 -- Analog Clock App
Elm Tutorial Part 4 -- Analog Clock App
Tensor Programming
7 Elm Tutorial part 5 -- Snake Game
Elm Tutorial part 5 -- Snake Game
Tensor Programming
8 Elm Tutorial part 6 -- Calculator
Elm Tutorial part 6 -- Calculator
Tensor Programming
9 Go Tutorial part 1 -- Hello World and Static File Server
Go Tutorial part 1 -- Hello World and Static File Server
Tensor Programming
10 Go Tutorial part 2 -- Web Crawler
Go Tutorial part 2 -- Web Crawler
Tensor Programming
11 Go Tutorial Part 3 (Web App part 1)
Go Tutorial Part 3 (Web App part 1)
Tensor Programming
12 Go tutorial Part 4 (Web tutorial part 2) - Using templates
Go tutorial Part 4 (Web tutorial part 2) - Using templates
Tensor Programming
13 Go tutorial part 5 (web app part 3)
Go tutorial part 5 (web app part 3)
Tensor Programming
14 Go tutorial part 6 (webapp part 4)
Go tutorial part 6 (webapp part 4)
Tensor Programming
15 Go tutorial part 7 (web app part 5)
Go tutorial part 7 (web app part 5)
Tensor Programming
16 Go tutorial part 8 (Web app part 6)
Go tutorial part 8 (Web app part 6)
Tensor Programming
17 Go tutorial Part 9 (web tutorial part 7)
Go tutorial Part 9 (web tutorial part 7)
Tensor Programming
18 Go tutorial Part 10 (web app part 8)
Go tutorial Part 10 (web app part 8)
Tensor Programming
19 Go tutorial Part 11 (Web app Part 9)
Go tutorial Part 11 (Web app Part 9)
Tensor Programming
20 Go Tutorial Part 12 (Web app Part 10)
Go Tutorial Part 12 (Web app Part 10)
Tensor Programming
21 Go Tutorial Part 13 (Web app Part 11)
Go Tutorial Part 13 (Web app Part 11)
Tensor Programming
22 Looking at Elm 0.18
Looking at Elm 0.18
Tensor Programming
23 Go tutorial Part 14 (Web tutorial part 12)
Go tutorial Part 14 (Web tutorial part 12)
Tensor Programming
24 Go tutorial Part 15 (Web tutorial part 13)
Go tutorial Part 15 (Web tutorial part 13)
Tensor Programming
25 Go tutorial part 16 (web app part 14)
Go tutorial part 16 (web app part 14)
Tensor Programming
26 Elm Tutorial Part 7 (SPA part 1)
Elm Tutorial Part 7 (SPA part 1)
Tensor Programming
27 Elm Tutorial Part 8 (SPA Part 2)
Elm Tutorial Part 8 (SPA Part 2)
Tensor Programming
28 Electron Elm Tutorial
Electron Elm Tutorial
Tensor Programming
29 Go tutorial part 17 (web app part 15)
Go tutorial part 17 (web app part 15)
Tensor Programming
30 Up and Coming Programming Languages and Technologies for 2017
Up and Coming Programming Languages and Technologies for 2017
Tensor Programming
31 elixir tutorial part 1
elixir tutorial part 1
Tensor Programming
32 elixir tutorial part 2
elixir tutorial part 2
Tensor Programming
33 Elixir tutorial Part 3 (GenServer and Supervisor)
Elixir tutorial Part 3 (GenServer and Supervisor)
Tensor Programming
34 Elixir Tutorial Part 4 (GenStage)
Elixir Tutorial Part 4 (GenStage)
Tensor Programming
35 Elixir Tutorial Part 5 (Plug and Cowboy)
Elixir Tutorial Part 5 (Plug and Cowboy)
Tensor Programming
36 Phoenix Framework Tutorial Part 1 (elixir part 6)
Phoenix Framework Tutorial Part 1 (elixir part 6)
Tensor Programming
37 Phoenix Framework Tutorial Part 2  (elixir part 7)
Phoenix Framework Tutorial Part 2 (elixir part 7)
Tensor Programming
38 Phoenix Framework Tutorial Part 3 (elixir part 8)
Phoenix Framework Tutorial Part 3 (elixir part 8)
Tensor Programming
39 A Intro to Clojure and Clojure Syntax
A Intro to Clojure and Clojure Syntax
Tensor Programming
40 An Update about the channel
An Update about the channel
Tensor Programming
41 Intro to Rustlang (Setup and Primitives)
Intro to Rustlang (Setup and Primitives)
Tensor Programming
42 Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Tensor Programming
43 Intro to Rustlang (Ownership and Borrowing)
Intro to Rustlang (Ownership and Borrowing)
Tensor Programming
44 Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Tensor Programming
45 Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Tensor Programming
46 Intro to RustLang (Enums and Options)
Intro to RustLang (Enums and Options)
Tensor Programming
47 Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Tensor Programming
48 Rustlang Project: Snake Game
Rustlang Project: Snake Game
Tensor Programming
49 Intro to Rustlang (Traits and Generic Types)
Intro to Rustlang (Traits and Generic Types)
Tensor Programming
50 Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Tensor Programming
51 Intro to Rust-lang (Modules and Lifetimes)
Intro to Rust-lang (Modules and Lifetimes)
Tensor Programming
52 Intro to Rust-lang (Macros and Metaprogramming)
Intro to Rust-lang (Macros and Metaprogramming)
Tensor Programming
53 Intro to Rust-lang (Error Handling)
Intro to Rust-lang (Error Handling)
Tensor Programming
54 Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Tensor Programming
55 Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Tensor Programming
56 Rustlang Project: Port Sniffer CLI
Rustlang Project: Port Sniffer CLI
Tensor Programming
57 Rustlang Project: Chat Application
Rustlang Project: Chat Application
Tensor Programming
58 Rustlang Project: CLI Toy Blockchain
Rustlang Project: CLI Toy Blockchain
Tensor Programming
59 Intro to Rust-lang (Setting up a Development Environment)
Intro to Rust-lang (Setting up a Development Environment)
Tensor Programming
60 Intro to Rust-lang (Building a Web API with Iron)
Intro to Rust-lang (Building a Web API with Iron)
Tensor Programming

This video teaches how to use Provider and ChangeNotifiers for state management in Flutter, along with Built Value for immutable data collections and JSON serialization, while consuming the Hacker News API. It also showcases the use of MultiProvider, ChangeNotifierProvider, and StreamBuilder for handling streams and managing state.

Key Takeaways
  1. Configure Provider for state management
  2. Use Built Value for immutable data collections
  3. Consume Hacker News API for data retrieval
  4. Use ChangeNotifier for data updates
  5. Implement MultiProvider for state management
  6. Use StreamBuilder for stream handling
💡 The video demonstrates how to use Provider and ChangeNotifiers for state management in Flutter, along with Built Value for immutable data collections and JSON serialization, while consuming the Hacker News API.

Related Reads

📰
Origin Part 20: Gradient Pollution
Learn to identify and mitigate gradient pollution in machine learning models to improve their performance and reliability
Dev.to · Josh T
📰
Omnist: I Turned My Sixteen-Year-Old PhD Research Into a Personal Open Source Project in Two Weeks
Turn research into a personal open source project by applying skills from 16 years ago to modern tools and technologies
Dev.to · Thomas Lee
📰
Why Great Developers Don't Learn More — They Learn With More Intention
Great developers learn with intention, not just more, to improve their skills
Dev.to · PyNyx
📰
The End of XGBoost? No. The End of Three Weeks of Tuning.
Learn how Google's TabFM predicts on tabular data with zero training, potentially reducing the need for extensive XGBoost tuning
Medium · Data Science
Up next
SQLite3 Tutorial - Learn SQL for Python in 17 Minutes
Thomas Janssen
Watch →