#Google's Flutter Tutorial - BLOC for State Management - Real Example (coderzheaven.com)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back to another flutter tutorial in this video we will see how to use block 4 state management in flutter with the help of a real world example before that if you haven't subscribed to my channel please subscribe and support so let's start as usual i'll be starting with an empty template with just a container set as home with a white background so let's create a new folder screens i'm going to create a new screen album screen which is a stateful widget album screen let's import the material package and the build function will return is coupled with an above and the title is going to say albums and let's set the body which is a container with a child let's write a new function body which is going to return a column and the children let's leave it empty for now we'll be filling it later now let's go back to our main.file and set this screen as home so home album screen you can see the output in the simulator on the right side now let's create a new folder named api here we will write some services to get the data so let's create a new file services dot dot let's go to the internet and get the get some fake json services so that we can use it in our example so if you go to jsonplaceholder.typical.com you can see so many fake services i'm going to use this one the album service now to get the data from the service we need to have the http package so let's copy it and open the pub spec yaml file and paste it under the dependencies so for this demo we need the flutter block equatable and the http package make sure to call flutter packages get and install the package for your application now let's go to the services.file and import the http package now i'm going to create a new class which is abstract called albums repo the next thing is we need to have a model class for our response so let me copy the response and go to app.chiptype.io and we can generate the model classes from here so let me copy and paste it here and give it the name album and copy the model class and i'm going to create a new folder and create a new file i'm going to name it albums list dot dot and paste the model classes there okay now we have the model classes for parsing the json from the service all right now let's go back to our services.art file and write a new function future list of album so this function is going to return a list of albums okay so this is a abstract class so let's create a new class album services which is going to implement this abstract class so we need to override that method and implement it so uri uri is equal to uri dot https and we need the authority and the path so create a static constant base url is equal to let me copy the url paste it there and another static constant get albums that is slash albums okay and we can use the base urls authority and the path will be get albums and this method is going to be asynchronous since it is a web service call so response is equal to await http dot get and pass in the uri and the response will be the list of albums so list of albums albums is equal to album from json and pass in the response start body as you have seen the album from json is the method from the model class that we generated all right now we have the response parsed and returned but we haven't written any code to cache servers correct for that i'm going to create a new class and i'm going to name it exceptions.dart and let's write some classes that will represent the different types of errors the first one is the no internet exception it's going to have a message and the constructor will accept the message and similarly we are going to have the new service found exception which is 4.4 and another exception invalid format exception and another exception which is not exception so if any of the above exceptions are not caught we are going to throw the unknown exception all right so our basic setup is ready now we are going to actually start with the block so for that i'm going to create a new folder so for each service i'm going to create a new folder and here we have only one service so a folder block and within that i'm going to create a new folder albums so this block whatever i write in here inside the albums folder is for the albums list service okay and the related ui so block. so what the block does is it simply takes an event and a state and it's going to return a new state which will be used to update our ui that's what we are going to do in few minutes so watch till the end so as i said let's start by creating the events so events dot dot and under file states dot and let's go to the events file and create the event album events and here we have only one event which is let's album our events part is done now let's try to identify the states when we are trying to fetch albums for that i am going to create an abstract class album state which is going to extend equitable equatable will help us to compare two objects with the help of the properties of that objects that we provide so let's declare the states the first one is the album's loading state so these are our states uh it can be any any name or any uh anything you want okay so it's telling us to override a method so the method we are going to override is to help equatable to compare to objects with help of its properties so for simplicity we'll keep it empty now let's declare the other states which is the album loaded state so these are the states that we are going to receive in the ui so name it accordingly the third one is the album list error or album error whatever you want so the album's loaded state will have the list of albums that we receive in the ui the constructor is going to accept list of albums and similarly in the error it's going to have a error member variable and the constructor will accept the error so in our case the error can be any type of the exceptions that we declared earlier our states are also complete now let's go to the block.file and create a new class albums block that's going to extend block and as i said earlier it's going to accept events and state so here album events and albums state import the flutter block and create a constructor that will accept a initial state so albums block and call super with the initial state sorry i forgot to declare a initial state class here in the states so let's do it now albums init state and you can have your own initial values here i'm going to keep it empty for this demo and we need to override one more method that is the map event to state that is needed by block so let's implement that method all right now we have the even here so when we trigger some event it's going to come here and we need to identify each event and act accordingly let's declare and the variable final albums repo so that this blog will have access to the services so that it will it can call and get the data from these services and under variable list of album this is optional you can have it inside the map even to state as well all right we need to initialize the album's repo variable so pass it with the constructor in the albums block now let's go to the map even to state method this will all make sense in a short while so don't worry about it so here we will identify which is the event here we have only one event which is feature albums and when this event occurs we need to return the state to the ui so call yield albums loading which is the first state but before that we need to make this method a thing star then only we can call yield so let me tell you what yield and return will do yield and return will both return whatever is coming after that so here yield is going to return the album's loading state but the difference is that it's not going to terminate this function like return but it will continue executing the next line and the lines coming after that but if you are using return it's going to terminate the function there return album's loading will terminate there and the rest of the code will not be executed if you are using return so that's what yield can do you can return data in between the execution all right so initially we are returning the album's loading state and we are calling the help bumps list service so once we have the albums we are going to return the albums loaded state so remember albums loaded state has albums parameter so if you go there you can see we already declared the albums parameter so we can pass in the albums there so that when we return or yield the albums loaded state to the ui we will have the data as well so that we can update in the ui all right so we have the very basic setup ready without the error caching so let's try to implement this in the ui so let's go to the main.well and here comes the main part we need to wrap the screen that wants to listen to the corresponding block updates with a widget called block provider so album screen is the screen that want to get the updates from the albums blog right so we want to wrap the album screen with the block provider so that's what we are going to do next so remember whichever screens or widgets you want to get updates from a particular block you need to wrap those widgets with the block provider so block provider create that's going to take a context and we need to return the corresponding block so here it's the album's blog so handboom's blog and albums blog will accept the albums repo so here it is the albums services so album screen needs to get data from the album services so the blog provider will provide the data to the child which is the album screen now we need to update the ui so i am overriding the init state and calling a new method load albums which is an asynchronous method and we need to import the flutter block here which will provide us with the context so context dot block and that is of type album block which is a stream controller so we fire events by adding even to it so the event that we are firing is fetch albums so this will fire the block which is going to come here and it's going to return the album's loading state to the ui but we haven't written any code to listen it in the ui right so let's write a blog builder here which is which is a widget that we can use to update the ui so passing the albums block and album state and it's going to take the builder and builder needs to return the ui based on the state so that will accept the context and album state and the state will have the data that we are returning from the block so if you go back to the album state class you can see the different data that we are returning so let's check if the state is album list error so if it is error we want to show a text with an error in the ui and if the state is albums loaded that means the service is in success and we have the data so otherwise we will show a progress indicator so you can see in the ui it's showing a progress indicator now let's write a method to list the albums in the ui so method list which will take a list of albums as parameter and it's going to return a expanded widget which is going to have a child which is a listview builder and the item builder will have the context which we are ignoring for now and the second parameter is the index and get the corresponding album from the index and we will show the album dot title in ls view let's set the item count as well which is the albums dot length all right now let's use the list inside the album's loaded state so list of albums is equal to state dot albums and return list and pass in albums now let's refresh the app and see if the data is loading okay refresh but there is some error which we haven't got yet so when we trigger the event it's going to come here and it's going to call the get albums list so here we don't need the https because we already have it in the api right let's refresh okay now we have the data let me show you how the data flow is so let's put a breakpoint here and when we first load it's going to the progress indicator and second time it's coming to the albums loaded and it has the list of albums which we are displaying in the ui okay now let's try to cast the errors for that i'm going to put a try catch here and move the service call inside the try catch and i'm removing the on catch removing the catch and replacing it with one socket exception and the second one we are going to catch is the on http exception and the third one is format exception and finally catch block so all other errors will come to this catch block and now we will return the error state back to the ui so that we can update the ui accordingly so on socket exception i'm going to return or yield the album list error and the error is our custom exception which is the no internet exception with the message no internet so similarly in on http exception we will change the exception to no service found exception and the third one is the invalid format exception let's update this second error to no service found and the third one to invalid response format and inside the cache we will return the unknown exception with a known error message now we will try to replicate an error okay so you can see in the ui it's displaying error let's get the error from the state which is the exception and we'll get a message from that exception and see what is error so you can see that's the error so that will be our dot message so you can see that it's no internet all right now let's create some widgets to display the error properly so i'm gonna say error import the material package and return a container with a text it's going to accept a string message in the constructor which is a named parameter and the text will display the message so these are all part of making widgets reusable so i have made a couple of videos based on this i'll be providing the link to it in the description i think i have a conflict here so let me rename the error to error text all right now it's importing let's give it the message we will try to customize the widget again by giving a text style with a font size of and a color of red now we will make it center all right now to the center of the page now it looks good so similarly you can customize any widget so that you can use it throughout your application so that it becomes a reusable widget so if you want to learn more about reusable widgets i'll be providing the link to it in the description so similar to that let's try to customize our list row so create listrow. and create a widget list row that's going to return a container with a padding of 20 and a child which is a column with a main axis alignment to start sorry not here main axis alignment to start and cross axis alignment to start and this widget is going to accept album as parameter so let's row and album and text will display album dot title and optionally you can display the user id as well which is an integer now we will go and replace the text in the list with the list row and pass in the album all right now it looks good let's try to customize the title in the list view so style a new text type with a font size of 20 okay now it looks a little bigger and let's add a divider as well all right similarly let me add a custom loading indicator with a new class loading and that's going to return an expanded widget with a child center and child a circular progress indicator and we will use this loading inside the block okay now you can see that it's showing at the center the reason behind creating all these reusable widgets is because in the second part of this tutorial we will be using block to theme our app so that we can reuse these widgets and make our app look uniform now let's try adding a retry functionality when there is some error so i am deliberately making an error and let's go to the ui album screen and we'll customize the message so string message is equal to error dot message and we will add tab to retry and we will go to the error text widget and we will centralize the content first and we will add a new parameter to the error text widget which is a function so when we tap on the error text it needs to trigger the reload of the albums correct so on tap and let's wrap the container with a ink well with it or a gesture detector whichever you want and call the on tab and back in the ui set on tab to call the load albums function so here you can see it's trying to reload but still it is error let's try to remove that error okay so that way you can implement a retry functionality or any way you want so this is one of the ways to do it so that's the whole thing so you can see we have different states here and we will be triggering these states based on the events uh so so if you go to events we have only one even here and uh so this is a block file so when we trigger the events with the state this is going to return a new state so initially it will be loading it will be returning back the loading event and when it is loaded and it will be returning back a album is loaded even so when it is loading event the block builder will receive the state and we have the corresponding ui which is the loading and when it is loaded and we have the data albums loaded will return the list of albums to the ui where we have set the albums so when it is when the ui receives it we will display a list and when there is some error we will display an error with it and with the help of block even you can make this widget stateless and you can trigger this in some other way so with the helper block you can make even the whole application stateless so that's the beauty of block so make sure you add the block provider around the class you want to listen and the services and the logic will be in the block so that will return the appropriate state back to the ui which will be uh which the block builder will listen and we can update the ui so that's a whole flow and that's all in this video if you like this video or if you found this video useful please don't forget to like subscribe and share that will be a big support for me also please don't forget to hit the bell icon for notifications so that you will get instant notifications when i upload new videos the second part of this tutorial will be coming soon so please hit the bell icon like share and subscribe thanks for watching and see you in the next video until then bye
Info
Channel: Mobile Programmer
Views: 15,423
Rating: undefined out of 5
Keywords: Flutter state management, flutter examples, flutter BLOC, flutter tutorials, android flutter, ios flutter, code flutter, flutter dart, learn flutter, google dart, single page application, flutter sqflite, flutter SQL CRUD, flutter animations, flutter chat app, flutter save data, flutter code tutorials, flutter admob, flutter state, flutter redux, flutter provider
Id: sDVU2JgQBJ8
Channel Id: undefined
Length: 26min 38sec (1598 seconds)
Published: Mon Oct 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.