BLoC Pattern with Flutter || State Management (Part 2)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hey everybody what's up! Welcome back to channel CodeX. This is your host Afzal and in today's video i'm gonna talk about the fundamentals of BLoC pattern. In recent video i have covered the implementation part and this video i'm going to talk the best practices inside BLoC pattern, how to close it how to create multiple subscription and all those stuff we're gonna talk and at the end i'm going to show you one live example with the news api and that i'm going to integrate with the help of BLoC pattern so all that we're gonna do in this video make sure to watch full video and we are gonna start right after this intro now we are inside visual studio code and as you can see we have this two stream controller which we created in our previous tutorial and if you haven't seen that i'll put link in the description you can go ahead and watch that but that's totally fine because you know we're just going to talk about the fundamentals the basic stuff about uh stream controller and block pattern so you can watch this video first and then you can jump to the second video all right so if you can see over here there's a blue you know zig-zag line and what it says that there's something missing there's something needs to be done if you hover on that it says close instance of dart core sink. what it means that this stream controller has been created but at nowhere this has been closed so what happens whenever you create a stream controller and whenever you are trying to listen to the stream it has to be closed because what will happen once your page gets destroyed when your variable gets destroyed this stream will still be listening and the pointer will be like it's pointing nowhere but it is taking the memory so if you don't want to have memory leak inside your application you have to make sure that you close all the streams okay? no matter how many streams you create depending on your need but finally you have to close it and the way we are going to do that is create a dispose method. Literally you can name anything you want but this pose makes more sense right because we are trying to close it and it even matches with the page dispose method so i'm just going to say or i can just copy this one this is stream controller dot close this is what you have to do at the first step so whenever you create stream controller make sure to close it and now if you go up this blue underline has been removed same thing we will do for the other stream controller just say close but we are not done yet we created this method but from nowhere we are calling it so we have to decide from which place we have to call this dispose it's very simple if i go back to this counter example which is over here i created the instance of counter BLoC so what i will do once the page disposes at that situation so i'll override dispose method and once this page is going to dispose that time i will use counterBLoC.dispose() method it's that simple so now actually when your page will destroy it will destroy all the stream controller it will actually stop listening for any event further and it will prevent any memory leak possible so that's all about closing your stream controller now let's move to the next topic where we'll talk about the subscription so whenever you create stream controller just like that how you can have a single subscription and how you can create a broadcasting one so before we jump to the subscription topic i want to give a shout out for the channel members and here it is. Thank you so much Ahmad Shaikh and Sam S for taking subscription of this channel. I really appreciate that and tomorrow which is saturday 5th of september i'm going to do a live stream dedicated to my pro members and if you guys are thinking how to become a part of that live stream go ahead to my channel and click on that join button next to subscribe and take a membership so at this point of time we have a small community so our communication will be one to one we all can discuss and talk about flutter and other mobile stuff in a close discussion so make sure to do that and let's jump back to the tutorial so i was talking about single subscription and broadcasting so if you define your stream controller this way it creates a single subscription stream controller what does it mean that at any point of time in the life cycle of stream controller there can be only one subscriber okay so whoever is listening there can be only one person who's listening to the events or or outcome of the stream and if someone else tries to listen to that it will give exception that there's already a listener for that so now you'll be saying okay for event stream controller you created a listener right so the stream of that is being listened but at no point of time you have created a listener for state stream controller counter stream right so why is that like why nobody is listening to the counter stream so i'll tell you the reason because whenever you create a stream builder and you provide stream over here like counter stream is being used over here this is actually listening to that stream controller so what will happen if you provide your stream in the stream builder and then explicitly if you try to listen over here it's going to give you exception and that is like most common exception people are googling uh why i'm getting this duplicate exception why i'm getting this already subscribed or something like that because you have already assigned a listener for it once you use the stream builder you are already listening to the events okay and then if you try to do it explicitly over here it is going to give you exception so that's why i'm using the uh i'm using the second uh stream controller to listen for the change and if in certain situation if you want to listen to your stream controller at multiple places you can do that of course with the help of broadcast and the way you write it just put broadcast like this so now what will happen that this stream controller is now broadcasting so at one place you're listening over here okay and you can have another listener as well so here i can write control like this let me just format it and then i can say listen and it will not give any exception if i execute as well so let me just rebuild and show you real quick i'm doing all the execution but it's still it's working fine but as soon as i remove the broadcast let me show you that as well let me just rebuild and you see so now it is started giving exception that the stream has already been listened to so now i hope you got the point whenever you create stream controller this way it creates a single subscription so you can only listen once and if you are already using that your user interface it means that you have already listened to it so if you want to create something where you want to have a multiple listener go ahead and make it a broadcast so so far we have seen how to work with the stream controller how to close it how to take single subscription broadcast and all those events all right now we're going to talk about the user perspective like how user interface we can handle different situation so if you see over here inside my stream builder i hope my screen is visible yep so inside my stream builder here i've just returned a text without checking any information so that's not actually a good practice because in this video i'm just going to talk about the standard practices best practices for uh stream controller and block pattern so first thing which you have to check is snapshot.data and this is like fairly common if even if you are implementing future builder uh you're working with blog you're working with provider anytime you have to check whether the data is available or not all right it should be has data okay and then let me just restart so what i'm checking is whether there's a data available in this snapshot or not and apart from that you can check different states of snapshot like connectivity status so i'm just going to say snapshot dot connectivity state and it has a lot of state just like just to show you connectivitystate.active.done.net so if dot none dot it's like trying to communicate to your server get the data it will be active state so you can show uh progress dialog progress indicator something like that if it is done then you can show like if you are doing some transaction and if the connection state says done you can show a tick mark something like that if it's waiting like if it's in the queue you can show that particular message so there's a different way of handling your data inside your stream builder so depending on the situation depending on whether it has data it has what is the connection state you can define a different different widget for that and also there's something called if snapshot has error so if snapshot has error so what happens whenever something goes wrong in your uh implementation part and something throws exception that time you can handle that and send your custom error message so if something goes wrong you can print that error message over here or you can just say snapshot dot error okay so that is how you handle different different situation different different scenario connection state inside your stream builder if you are working with a block pattern or a stream controller it may have data it may have error it may have different connection state and all that you can handle inside your stream builder so that is all about some of the best practices inside block pattern now let's move to actual example where i'll consume one rest api for news application and that i'm going to show with the help of blog bannon before we move to that it's time to give appreciation to our viewers who are commenting who are liking my videos so here is the comment of the week and channel of the week thank you so much for providing your comment it really helps me to improve my video and you know to come up with the better quality content for you guys and if you're thinking how to come in the feature comment or feature channel next time you just have to go to comment section and write something about this video what you felt and next time you can come in the feature comment and feature channel so let's get back to the video and implement the live news inside flood application with the help of block okay for that what i'm going to do i'm going to copy a lot of code from my existing repository so don't worry let me just show you i have already created how to consume rest api you can go ahead and watch this video i'll put link in the description for this video so it's fairly simple you just call api and get the data and i have already shared a source code for you guys so you can go to my github profile and you can go through the code if you want so i'm going to just copy this information real quick so that we don't waste time implementing all these things so there's a simple method over here which fetches data from the internet so i'm just going to copy that in our code and before we do that let's create another blog so this time i'll call news blog dot dart and let me show you my mobile as well class news blog so this is the live example which i'm showing it's fetching the data from the wall street news so you can get the news in your application and what i'm going to do is copy this to stream controller real quick because we don't want to repeat ourselves i have already shown how to work with the stream controller and how it's very easy like if you want to go check the previous video this stream controller comes from a sink so we'll just resolve that real quick okay and this counter action instead of counteraction will create our custom action so i'll say enum news action this is just for demo purpose and unreal uh example you can create what you want so i'm just going to say fetch delete we can fetch the news articles we can delete some so like that i've created two uh enum and that action i'm going to use over here so what will be the event of our news either user can fetch it or delete it this is the event and this is the state what it's going to give out so it's not going to give integer instead it's going to give list of sorry list of articles right now we don't have this article defined let me just okay before we grab that let me just put this everywhere okay so basically our state gives list of article and our input it takes uh you know action from the user so i'm going to go ahead in my git source and copy the entire model just real quick it's very simple thing i just converted the json to model using the online tool quick type so i'm going to call news info dot dart okay and i'm going to paste this entire thing so now is everything fine over here nothing wrong inside news blog now if i resolve it's going to resolve from news info popping so we integrated the model inside our blog now what we have to do once this news blog gets created we have to listen for the change what user is asking so as soon as the event stream changes user is asking for something we have to listen for that and then depending on the user request if the user has requested sorry if the user has provided the event which is equal to news action why it's not giving suggestion dot fetch like if it's user is trying to fetch the news we have to do this action if user is trying to you know uh like delete something we can do other action but i'm just going to show you simple example of fetch what is what is wrong here okay if should be small all right and now at this point of time i'm going to copy this model sorry not the model i'm going to copy this service which is fairly simple just few lines of code only this method i'm going to copy and paste over here it takes a json which is inbuilt thing from dot dot convert takes this url so i'm going to remove that and add our custom url and the http of course we have to add http library so i'm just going to copy that as well where where it should be in the pub spec eml file right where it went yeah right over here so i'm just going to copy and paste inside our dependencies as simple as that i hope you people are enjoying because now actually we started implementing something uh first part i know it was a little boring because i was talking about you know theoretical part and it's sometime it's important to know theory as well because all this stuff like memory leak and uh you know single subscription multiple subscription these things we can only come to know uh after reading the theory or at least listening to it okay so i'm just importing this library in my blog class so everything is fine everything is resolved so now user is giving the action of fetch we just have to call get news just like that and we'll make it a wait because it's a future so it will come after some time and i'll capture that in say for example news variable because we are using await we have to mark it as sync for sure so it is a full model like where news articles are there news counts are there everything is there inside this we just interested in news dot articles okay so now we have to sync this information this list of articles inside our uh state sync so here in this straight stream controller okay it's named countersink so let me just change it real quick instead of countersink let us call it uh you know news sync so that it makes more sense instead of control stream we'll make it news stream just like that so whatever information we have we have to put that inside our new sync so i'll say newsthing dot add and we will put all these articles easy busy right so far so good everything you understood we are just implementing the block pattern first and then we will create a user interface for that so this time we are going reverse way all right so everything looks fine to me we are adding all the events let's handle a failure case as well so say for example something goes wrong while trying to fetch that so i'm going to wrap everything inside or maybe just for fetch so if something goes wrong while fetching the data i can wrap everything okay click on this bulb icon here and say try catch and when something goes wrong just give a new thing so to the same thing we will add instead of adding data we will add error this time and i will say something went wrong just a generic message and this is what it will display on the user interface so if you add error from here it is going to have snapshot dot hazard and from there you can access this same message you can even put your own custom model if you want this is up to you like what you want to provide as an error so that is all fine now even like everything is fine everything is looking good to me let's go ahead and run this and of course we have to create a page for that i'm just adding all the files in the lib directory so don't do that in your actual project so i'm just going to write news page dot dot because i don't want to waste your time because this is not a basic lecture where i'll talk about you know managing a folder and all stuff i'm just going little bit fast so that we can cover a lot of things import material and using stateful i'm going to create new speech very easy and then i'm going to say scaffold or better i can copy this entire thing from here so i'll go to lib here i have managed the folder structure if you want to follow that follow this structure i'm just going to copy the build method over here i'm not sure where it ends just copy till this point okay i hope it's right yep it's totally fine and this news model come from the news info dart and everything is fine all right so it has something called okay so let's copy this as well it will be helpful for us fine so what is happening if you if you see the api tutorial which i've created there we have implemented a api manager and on init of the page we are calling that api manager and getting data assigned to this one and let me just also resolve this date format it comes from the international education package everything is fine still there's one error which is api manager right so instead of creating future model what i'm gonna do you already know we have to create an instance of our block so the way we do it final you can name whatever you want news blog and it will be of type news blog so we got our instance of news blog and using this news blog say news blog what we have to call is we have to put uh event inside our stream controller so i'll say eventsync dot add and what event we have to provide news action dot fetch you can of course you can call delete and for that you'll have to write a delete implementation but i'm going to take example of only fetch let me show you my screen as well so basically what i have done is i have created this news blog instance and whenever page initializes at that time i'm just putting one event in the event stream that i want to fetch all the news items okay and then of course we have to listen to the stream changes so instead of future builder it will become stream builder and see how easy it is you just change future to stream and you are good to go so flutter makes it very easy with the help of their widget hierarchy that everything works fine it's very simple even though like stream builder you have stream you have builder future builder it's future it's builder it's very simple now the stream builder you can see that it's accepting news model but whereas our blog it provides list of articles so we have to change that implementation the news model was previous implementation okay so i'll say i want list of articles that's fine and it should come from news blog of course news blog dot stream news stream right so this is so far so good and now we are not listening the whole model we are only taking list of articles so now we can remove these articles because this data actually is a list of article okay so i can just get rid of this keyword from here and i think everything is fine so let's give it a run i'm going to go to my main page and instead of calling my home page i'll call news page just like that and it doesn't accept any title so let me remove that so when i run my application i'm getting this error that articles was called on null and the reason we have to check inside our blog so let's go to the news blog and here it tries to fetch that okay so what happened uh it's trying to add news articles and to be honest it didn't fetch anything and something happen of course we can handle that so instead like we have to put a check over here if news not equal to null this is something extra which came in between so i'm i just want to show you how to handle those things as well so call news think dot ad only when your news is not null like you actually fit some data from the internet so currently there's no data because i didn't provided the url itself so it's giving exception so if your news is not null then only add it to articles else what you do is give it a error so i'm just going to put this line okay and let me just recompile it once again so now you can see that it's trying to just load load and load so it's not handling the has error part because it has actually received an error so we can go ahead and quickly change that implementation so i'm going to implement if sorry snapshot dot has error then just return me a centered widget and inside that i'll just put simply a text widget okay yep that's fine and the value will be of course snapshot dot error okay so whatever user is providing that we're gonna display it back and if it's null it's a good idea to handle the null situation inside text you can just say error something like that okay now you can see that the user interface has updated with something went wrong so whenever there's a error happening inside your snapshot you can handle this way so let's go ahead and fix that error okay i'm going to provide the link i hope it should be there in the yeah it's there over here and i can just copy paste and of course it requires api key so let me just go to news org and get my api key if you want you can take your own api key okay so now things are fine if i re run the application let's just check so it reloads it fetches and we have the news article with the help of block pattern all right so what we did we wrote a simple implementation we just created these three files where actually our blog thing goes we have a news info where our model goes and this is a news page where we have defined the user interface so let me just close this counter block so let me just close this from news page first so once this page gets destroyed you know the drill right i have shown in the beginning so you have to overwrite what uh what you have to override dispose right okay inside this pose you just called news blog dot dispose that's it so i hope the names are same stream controller we are closing that and we are good to go i hope you people enjoyed the video let me just talk about the block library if you don't want to create all this complicated stuff you can go ahead and use the blog and blog flutterblock library now in future videos i'm going to focus on get x because a lot of people has recommended me on youtube comment some people have written me mail as well and actually when i started looking in the get x it's very very powerful you know you get the navigation routing mechanism everything handled you get a state management out of the box and you get a lot of other features like validators email validator storage you know all these fancy stuff you get just with the get its package okay so if you want to try that uh i'm planning to create tutorial on this series because many of people have requested let me know in the comment section what you feel about it whether i should do or not so that's it for this video guys i'll put link in the description whatever i have talked in between and of course i'll put link for my previous video where i have shown implementation how actually stream controller works okay give it a thumbs up if you have enjoyed the video subscribe the channel and if you want to support if you're kind enough to provide your support to codex channel go ahead and take membership and with that i promise whatever i take from you i am going to give back more than that so that's it for this video thank you so much for watching i will see you guys in the next
Info
Channel: CodeX
Views: 32,617
Rating: undefined out of 5
Keywords: design, flutter, tutorial, how to, android, ios, ui, latest, theme, app, Flutter ui, flutter tutorial, minimal design, flutter ui design, flutter ui, flutter animation, layout, gradient, learn flutter, flutter dart, flutter sdk, provider, codex, bloc, pattern, streamcontroller, streambuilder, sink, stream, state management, with flutter, flutter state management, flutter bloc pattern, flutter bloc, single subscription, broadcast, API, bloc pattern, flutter design pattern, flutter business logic
Id: K6ETAfGZl4k
Channel Id: undefined
Length: 27min 4sec (1624 seconds)
Published: Fri Sep 04 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.