JSON parsing with BLoC pattern in Flutter (flutter_bloc : 2.0.0)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone what's up today in this video we're gonna parse the JSON from an API using the block back now block stands for the business logic component and block pattern is a design pattern for separating business logic from from the UI layer now it needs a lot of work but fortunately there is a package available for simplifying the process of implementing the block pattern the package is the floral floral block I'll put the link in the description so our we're gonna purse the JSON from an API which is like this I'll put the link in the description you need to get and get the API key to use the API I have mine and the final URL will look something like this and this is the response from the API and our final F will look like this one there will be a list of articles and when I click on the items there will be another screen containing the description of that article ok so let's start it now let's have a brief overview of the block package that we're gonna use basically a block takes stream of events as inputs and converts them into a stream of states as output this package instructs the reactive aspects of the block pattern but then again let's have a quick view on some important terms there is something called events which is which is input to a block and these are actions on the screen such as button click and another term is States these are the output of block in block pattern using the face is changed based on the stream of received state so enough talking let's get started so first of all we need to and packages in the pub spell ml we're gonna use this 3 package one is obviously the flutter block another one is the HTTP package which is for the network call and additionally I'm using the equitable package which is for comparing value equality of the objects now let's create some folders here I already have created two one is areas for for putting resources like strings colors areas etc and inside I can use the images if we use images externally then I can put it in the inside there is for our ears folder and here is this string store dark file and here I'm using a static string which is the link of our URL so nothing nothing really and then there is the UI folder I will come it and come here later and also let's add some other folders like one for the block and other one is the data folder ok so inside the data folder we gonna have some models and our repositories so let's add two more folder here on its models and the other is a repository ok now what will be the model of our responses so this is the response from the API we need to create a model class for this response and fortunately there - to simplify the process of creating the model class let's just copy the responses and there is a tool this one just best response here and then click here this will automatically generate the model classes for us I'll put the link in the description so this is the model class that we're going to use so let's copy it copy and then paste it create a folder here get a file here like al-naimi this api result mmm model Dodge Dart okay and then test that code these are the model classes let's just rename this opera generated class to something this will be renamed this API result nada okay so this is there as a model class and I have renamed the name of it so it has three values three variables here you can see one is string status or that the response is successful or not another one is an integer the total number of results and finally the one which we are looking for the articles list of articles okay so this is the models model to us and let's create a repository for our app so let's create a repository so for that let's create a file article the repository got that and here I go I'm doing I'm going to create an abstract class let's try repository class article depository okay and what are the use cases here just a single one which is fetching the articles and so let's create a method for that and of course we're gonna get the articles as future so return type will be a future of list of articles article is a model class get articles so this is the repository class is the repository and strapless now let's implement it and we don't need to create a separate from whether you can create the class implementation class here so article with palsy tree implementation which cannot implement the struct class let me just create it okay now now time for logic for converting the parsing the JSON now let's learn it to use the HTTP package here for making the network comes so that's important HTTP dot dot s HTTP okay has returned of as we gonna get the articles as future so you need to use that I think you are here sink and let's use HTTP dogs to get and let's put the link here which is inside the strings class looking for it and strings dot click article URL so this is Daris in this way you're gonna respond get the response from the URL so let's put it in a variable variable response okay now let's check whether the response is successful or not so for that as is if the spawns dot status code spawns dot status code what's from here responds ah we have not awaited here we need to use that irate keyword because this is a future response so we need to have it here and then use the response dart status good if the status quo is 200 that means response is okay then we're gonna convert the response so let's first use the get the read JSON response so for that we need to convert that convert so let's use json dot decode decode the response ponds of the body okay this gonna give us an JSON response right I tell you something JSON object yeah this is gonna give us the JSON response but we need response as articles right it is the model class if you can remember are you gonna fresh this article subjects but here we are getting the JSON response so we need to convert it so first let's put the JSON response in a variable variable data okay and then convert the JSON response into our appropriate model if you look here there is a from jason method which gonna take a map of map and then convert it into our response model which is articles list of articles so let's use that result model cut from jason and let's ask Jason response here okay this is gonna give us the appropriate our list of articles okay so let's put it in a variable and this just articles okay what's wrong here Oh articles okay this is the articles variable of this model this one articles I'm gonna get a list of articles okay so now we can return this list return articles so that's all about getting the response from the J from the URL now there may be some exception when the response is not okay so let's handle it else if the response is okay then you're gonna purse we're gonna return this article but if it is not then you're gonna throw an exception that's it that's it so that's all about our repository class nothing much needed here so our data layer is ready okay now let's come to the core of this video which is the block better block now inside block folder we're gonna create we may have several blocks for the for our app but in this app we have a single block which is which is for fetching the articles so I'm gonna create another folder as article block and as I said earlier we need three things for for a block these are the state's events and a block file so let's create them print those fats first one is article even dot that second one article state dot dot and finally article Bach okay so let's move on to the event so what are the event in this app we have a single event which is fetching the article list from the API so just a single event right so let's create an abstract class for the event okay so let's create it abstract plus a tickle event event and we're gonna extend to the equitable class okay now we have the single event let's create it maybe this fetch articles even and we're gonna extend the struct class struct article even class article even we need to override a method which comes from the equitable package okay that's it that's all about the event now what are the state of our app think about the different states that we gonna get initially hina means start our app there should be a loading indicator because fetching the articles is a future future operation so it's obviously gonna take some times and in there during that time you're gonna should display a loading indicator so there should be a article loading state and then a state for the successful first a success and the fetching articles become success and another for the error there might be some errors and these are the three states and additionally it can use another state for as article initial State okay so let's create those state so just like the event we're gonna create an abstract class first abstract class article state is gonna extend clearable us okay now let's create the states aster on his article initial state and extend article state second one is for the loading state article loading stage let's hard one and articles are loaded article low depth state and another one for the errors article error state okay we need to override the method 1 method which comes with a credible package so just override that method now in the article initial state we do need to use any variable so we can make it empty saying goes here in the loading state empty but in the article loaded a state we have to handle the first articles so let's create a list of article articles okay then in the constructor article on your red state let's make it required let's make it required so for that are you gonna use a package which is beta dot touch now we can make it a recruit required this start name it has articles that sounds good okay and similarly hi an error occurs we should show an error message so string message in this dot message so that's all about the article state now let's move on to the article block file so this is the file how are you gonna convert we're gonna fetch the steak we're gonna map the event to state so let's make it ready first of all we need to import the block dot dot file that package and then create the + H is article block and we need to extend the block and a step parameter you to mention the article are the event and the state so even here is the article event and the state is article state right and we need to write two methods which are the initial state and maybe even two state so initial state will be is for the initial moment of our app so for that we already have created an estate here which is the article initial state so let's just use it article initial state okay now come to this method which is map even to state so what this method you're gonna do this gonna act in this actually gonna it takes events as extreme and then converts them into states as streams which are consumed by presentation layer may even to a state method is called whenever an event is added by presentation layer so here in this case when the event is added article loading article initial state is initially loaded initially initially gonna be called and then we need to handle the other states so let's first check the even for first though even though we have only a single event which is article just just a minute fresh articles event this one is the only event of our app so so if the event is this one I gonna handle it how also one more thing which is this may this map even to a state gonna return the states as string so for that we need to use this s Inc generator keyword and then I'm event is fresh articles event initially we're gonna yield the article load loading state not to Kelly loading right so it is just like the return keyword of any function it can compare it with the return for now and initially you're gonna display the loading indicator for that we are using this article loading state and then we need to get the responses I mean we need to fetch the articles so for that we need we need to use the article repository that means we have a dependency here on the article repository repository make it a required so from that let's import our meta dog shut okay and then is the required keyword they start repository okay and then let's fetch the articles from the repository or that we have this repository dog cat articles method and of course this is a future so we need to use the era keyword tech irate this one and we can put it in a variable a list of article okay so when the article fetching is completed then we can is the article loaded state right so is article loaded state is it typing mistake maybe let's copy the appropriate spelling yeah and then we need I need to pass the articles okay so that's all about fetching but remember there may be some exception while fetching may be some interaction like internet connection interruption or some other things so for that to be in the safe side we should use a try-catch block so let's use it a try catch block okay and then we should catch the exception and remember for exception for errors we have a separate state which is the article error state I guess article error yeah and then first message message message is a dot to string what was the name here oh we did not make it named parameter so let's make it main parameter are using the curly braces okay now that should be okay so that's all about the article block and our blog part is ready right we we are done with the events we are down in the states and also our article blog is ready so our blog part is ready to a layer is ready now only things remaining is the UI part so let's do it so now let's finish the UI part we have this main door dart file which which has a home page I'll show you the home page later but we need to use them we need to use a widget from the blog package which is the block provider let's use it block provider I will explain it block provider and as builder it you're gonna take the context context and then return return the block we are working with which is the article block article block yeah article block and it has a dependency on the repository so yes as a repository article is a Paul C 3 I am feel okay and then child as a child you can use our home page I'll show you the home page in a minute now let's let's talk about the block provider widget what is this so we are using block row very rigid from the flutter block package in order to make the instance of the block which is the article block available to the entire subtree block provider will automatically close the article block so we don't need to use stateful yet and then override the dispose method the disposing part will be done automatically so we don't need to use don't need to make this homepage stateful but then again we're gonna make it a stateful widget instead reason is there is no user action initially and the API gets called I mean on our app starts their own being a user interaction directly the API will be called so we need to call the block from the initial State method of the state religion so for that reason are you gonna make this home page as stateful widget right so this is the home page and I have made it a stateful and I have created the UI so let's have a brief discussion there is a you can see here there is an M bar for that I have used this scaffold regent and there is the Empire and in the M bar there are two buttons one for refreshing and the other one is just a simple button for showing the eyebrows frame okay nothing much and then an empty container as of now now we need to display different UI based on the states so for that I have created the UI for appropriate activity why for the states one for the loading state and the state is loading then we should I mean it we're gonna show the circular progress indicator and then I'm if there is any error then you're gonna show a text widget with the error message and if the parsing is a success then we're gonna show this are gonna call this Matt this method which is returning a ListView simple ListView nothing gorgeous and simple this view okay and for navigation for navigation purpose I will explain it later for navigation because I have created this true method okay nothing related to block there's some simple UI UI the data so let's our block is ready now we need to we need to call that block right so for that we should have an instance of the block that we just created so let's have an instance of that block which is article blog article block and we're gonna initialize it inside the native state but let's move here now the container is completely empty it is completely empty and as a child of this container are you gonna use and we a widget which is block builder drop builder reject and we should specify the block and the state as the type parameter yet article plop and their studies article stay okay so this is the block builder and a builder it takes the context and the state and then here we're gonna check that state and then you're going to return the appropriate UI based on the state so let's check the state's first if the state is our pickle initial state then you're gonna return something else if else if it is I'll snip say this article loading the state article loading a state then another UI and safe state is article load deck state and finally if there is any error the error state this article error state should be a separate device but even the article initial state an article loading a state will show this same UI the article the building but then again here created separate block here okay now let's return the appropriate UI for article initial state we're gonna display the loading indicator built the loading same goes for the this state it an built loading and if jason parsing is successful if we happy if we can successfully parse the articles then you're gonna return this part which is Bill article list they can build article lists and pasta articles which cannot get from the state yeah and finally if there is any error then return built error ey with the message State DOT message so let's have a look at the UI the loading UI is just a simple loading indicator error UI it's just a simple text region and build article list ey is simple ListView [Music] and there I have you stank well this tile and other UI parts right and that's all but remember we should show a toast message and there is an error right if you can show a toast message R or L so you can show a snake bug right so there is also another another widget from the dog package which is block listener and this man this widget is to listen to the different states right we can I can make the print message for the debugging purpose and you know if I can listen to the states so let's wrap this block builder if that widget which is block listener right and as type parameter we showed a short mention the attic and the block and the state is like the provider so let's mention it article block and articulate state and song and then listener it's gonna take a context and the state so if the state if the state is our typical error state then we should show a sting bar so for the scaffold dot off dot so sling her show singer content is a text widget and stage start message so that's all about showing the error message yes there will be a snake bar or with the error message also there is also there is a separate device from that error message which is a text widget at the center right so our UI part is also ready your part is also dated nuts input these articles UI part is also ready week we are fetching the stage and then showing the appropriate UI but nor so far we know where so far we have called the event right there is instance of the article block we need to add the event to the block so let's first initialize this article block here using the block provider block provider dot off okay so we need to initialize it and need to add the event here just mentioned our blog article of block okay so initialization is done and then let's add the even here which is edge articles even import it typing mistake just just a minute okay so everything is ready to go everything is ready to go and anything missing everything is ready oh okay let let me show the article detail page there and that is all so simple nothing serious here is the article detail page where we're gonna have the article object article object and you're gonna display the data in a list view just stay image widget and then a container with beta text widget and simply why nothing serious okay simple ey and then the article detail page which is even more simple there is nothing but some sorry the article detail page and then the about page about pages even more simple just a text widget and in the container in a container rigid so that's all we can we can now run the project now let's see so let's have a brief overview what we have learned initially we created this data layer with the models from other models appropriate models and then we created a repository class why are we actually parsing the JSON into our models which is a list of articles right and then let's have a look at the block files there are three files event state and block single event nothing nothing much a single event for this app which is such articles event and there are four states for this app which are initially stay loading a state loaded state and an error state and inside the block we are a year if extended there is block class and mentioned the event and state in the tank parameter and then we have shown for the initial state this article initial state is given and inside the map event to a state method we are actually converting the event with the appropriate state right so if the initially we are checking the event and then initially we are showing this article loading state and then articles are fetched if this is successful then this article loaded loaded state is ended with articles passed and if there is any error then this article error State is edit right so let's check yeah it's working perfectly initially there was a loading indicator and the app is and gets called and then the list of articles now let's click on article and then this is the error page okay if you like this video do subscribe to my channel let me know
Info
Channel: CODE VILLAGE
Views: 17,707
Rating: undefined out of 5
Keywords: Flutter, BLoC, flutter_bloc
Id: 27EP04T824Y
Channel Id: undefined
Length: 44min 54sec (2694 seconds)
Published: Sat Nov 16 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.