Flutter Async/Await & Futures Tutorial - Dart Asynchronous Programming Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
as syncronous programming is often a concept that a lot of beginners struggle with but if you want to level up as a developer then it's pertinent for you to understand this because this is going to give you the foundation in order to build amazing applications asynchronous programming is essential if you want to build real world applications that do real world things such as interacting with files on a system or making Network requests so in today's video I'm going to be breaking it down for you guys step by step and kind of giving you a guided path through which we're going to learn not only the basics of what a drinking programming is how Dart handles it but also some of the fundamental concepts related to it within the dart programming language and fter such as Futures await statements async functions and a whole bunch more so the first thing we should do is actually try to understand what ASN inness programming is I really like this definition that's provided to us by free code camp where it says that a stringiness programming is a way for a computer to handle multiple tasks simultaneously rather than executing them one after the other and what a synness programming allows a program to do is to continue working on other tasks while waiting for external events such as Network quests to occur so a good example of this would be let's think about an app that's going to fet some products from an API and then display them to the user if we're not going to be using as synchronous programming then what's basically going to happen is that when we actually go ahead and try to fetch the data from the internet for the products our application is going to hang up it's going to freeze the UI is not going to work anymore because we're waiting for the data to become available it has essentially blocked the execution of the program and now once the data is going to be available then the user can again interact with the application but I do not want this because this is not a good user experience so what I can do in this case is use asynchronous programming where what I'm going to do is tell the program that hi I want this data go fresh this data and once the data is available let me know and in the meantime you can do other stuff so this way the user can still in the app while the data is loading maybe go to the settings page do other things like that and then once the data is available then if they come back to the actual products page the products are being displayed to them and this way we can ensure that they have a good experience and similarly asynchronous programming might be used in scenarios where you are going to be running a long running tasks when you're uploading a video to YouTube you don't want the actual YouTube application to freeze up because uploading a video is going to take some time so what YouTube allows us as creators to do is to actually drag and drop our video in and start uploading the video but then I can go anywhere within YouTube Studio while my actual video is being uploaded and this is another example of fa synness programming but the easiest way you can think of it is that asynchronous programming as this definition mentions is a way for a computer program to handle multiple tasks simultaneously rather than executing them one after another so let's talk about how you can can work with asynchronous programming in flutter the most fundamental thing that comes to your mind is a future wherever you're going to see a future that usually pertains to some kind of an asynchronous programming scenario so what is a future let's talk about that first so what I like to tell people is that a future in do represents a value that is going to be available sometime in the future and a future basically is a promise you could think of as you're coming from the JavaScript world is that that hey this is going to be a value that's going to be available to you in the future and I will notify you of that so let's now take a look at on dartpad dodev which is an excellent website where you can write your Dart code within a web ID and then execute it a concrete example of what a future is how we Define it and how we work with it so what I'm going to be doing is basically creating a function and this is a mo function and I'm going to call it fetch data and what my function is going to do is that it's going to say that hey this function is going to return a future and then obviously the future is basically you could think of as a wraparound a value and a future says that hey in the future I'm going to provide you with the value and what is that value going to be well it could be anything that you want it to be it's going to be the value that gets returned by whatever operation that you're going to perform it's going to take some time to complete so in my case what I'd like to do is that once my operation completes I'm going to be returning a string so then my future is going to be of type string there we go and that's pretty much done and the S here needs to be uppercase then I'm going to say that this function is going to be called Fetch data like so and with this done the next thing that I'm going to be doing is opening the body up and then here I'm going to be defining the actual future so Futures can be defined in the lot of different ways what I'm going to be doing is using the futureed or delayed function which basically allows me to create a future using a duration object so I'm going to say that I'm going to have a future do delayed and then I'm going to say that the duration is going to be let's just say seconds two there we go and that's pretty much all we had to do and with this done let's do this let's remove the actual type for the future now and let's just say that we are just going to return a future and that's pretty much all we're going to be doing so basically this fet data function is going to return a future and this future is going to take 2 seconds to complete if this was a network request it might take a certain amount of time to complete and then what I can do is come within my main function and actually call fetch data and since this returns a future if I want to get notified when this future completes what I can do is actually chain on a then clause and what this basically says is that hey when this future completes which fetch data is going to return us a future I want you to run this function and then within this Den statement I can define an anonymous function like so and this function is going to be run once the future completes and this function is going to get as an argument pass to it the actual value that gets resoled when the future completes so in this case I'll call it we like so and with this done what I can do is say print and I can do future competed there we go and then I'm going to basically copy the statement paste it at the top and say future started and then do run and you're going to see that the application runs and then after 2 seconds it says future completed so this is basically an essence of how you work with asynchronous programming within flutter and now you're going to see he how can I run parallel tasks using this well if I go ahead and I do future started and then I'm going to do another print statement which is moving ahead you're going to see that firstly future started is going to get printed then moving ahead is going to be printed and then once the future resolves after 2 seconds future completed will be printed so what's basically Happening Here is that the first line of code is ran then it sees that it's a future fure so it runs it and then it moves on to the next line which is print moving ahead and then once the future completes it calls this function which we've defined as an anonys function in the den clause and then it basically does whatever it needs to do once the future completes so as you can see now we're running parallel tasks at once and our program is not blocking the main thread when we actually call the future so here I'd like to talk about an important fact in dark and that is about currency and isolates and as you can see on the official documentation for flutter it says that all D code runs in isolates and I don't want to confuse you guys too much but I'm just showing you guys so that you understand that Dart functions in a bit of a different manner than just traditional asynchronous programming where we have the concept of threads so basically isolates differ from threads in one simple way and that is that isolates have their own isol ated memory threads share memory isolates do not so the only way isolates can communicate with each other is through messaging and the way that works is that you have this main isolate that you can see and then this main isolate is what's running the actual flow of your application and what basically happens when we call the main function is that this is executed within the actual main isolate then we go ahead and call this function which Returns the future so that then what's happening here is that the actual operation that needs to happen for this future to resolve is pushed to another isolate and then we move to the next statement within our main isolate so that's basically how Futures work within flutter and this is basically all you need to know for now as a beginner so the next thing that we're going to be talking about is then what is an async function and what's an evade statement why do we use those well the reason we use those are for two things one is to improve the readability of our code because you can see here that if we have a bunch of Futures let's just say that I copy and do this that it becomes very difficult and cumbersome for somebody to understand what's going on it's a lot of function chaining and function chaining is something that at least I don't like so what you can do is instead of doing this use a async function and then an aate statement I'll show you how to use that and the second benefit of using async aate is that it ows us to basically reason about asynchronous operations much better because it makes asynchronous code appear like it's synchronous so I'll give you an example of this now as well let's just say that what I want to do is transform my fetch data function into a function that's going to return to me a string and it's also going to be a function that's going to be a sness so it's going to take some time to complete so the first thing that I can do is that I can say that hey since this function is going to be performing some kind of an as synness operation within it I'm going to mark it as async there we go and then after this is done the next thing that I'm going to be doing is basically using the await statement so what the await statement allows me to do now is basically stop the program from moving to the next line of code till this future resultes so once this future resultes then we'll move to the next Lane so in the next Lane what I'm going to be doing is returning a string like I had alluded to before for this function so I'm going to say that this function is going to return a string and again I'm going to say that the string will be future completed there we go and then what I'm going to do is go ahead and instead of using a future here say that now this function returns a string well if I do this you're going to see that we're going to get an error so the key KN among you might have already noticed so since this function has been marked as asynchronous it has to return a future and then since it's going to be returning a string that actual value that the future is going to be resolving to is going to be of type string so the return type here can't be string it has to be a future and then what is the specific type of the value that's going to be returned once the future results when in this case that's going to be string there we go and if I do this then it's not going to give me an error anymore so now once this done you can see that I've def find again some asynchronous piece of code but one it's easier for me to understand what's going on because um there are no more function chaining and the other thing is that it makes the code much more cleaner and easily understandable so now what's going to happen is that I can go ahead within my main function and I can say print future started and then what I can do is say that I'm going to do print and this time I'm going to do fetch data and you're going to see why I did it this way and then execute the function and then after that I'm going to say that we're going to print moving ahead if I go ahead and do this you're going to see that instantly we're going to get three statements printed out the first is going to be future started then it's giving me a weird output saying instance of future string I thought it's going to return a future completed and then moving ahead so what's basically Happening Here is that we call the first line of code we move to the next line of cod so we execute the function and we don't wait for this actual operation to complete we are not concerned with the actual return value from this future I just want to call this function move it to a separate isolate and then go on my Merry way and then I go ahead and called moving ahead but what if I want to actually wait for this actual operation to complete well in that case I can do the first thing that I'd show you which is to attach a then Clause to this which was like so and then just wait for the future to resolve so it's going to be this Anonymous function and then within this I can do print WI and that's pretty much all we have to do and with this if I go ahead and run it you're going to see that I'm going to do future started moving ahead and then future completed so the same thing that we were doing before but if my actual need is that I want for these statements to be executed one after another even if it's an asynchronous operation I need for the future to actually resolve before I move to the next line then what I can do is use the await statement so for that what I'm going to do is basically say that I'm going to do a weit and then I'm going to do fetch data like so and then this function is going to as you can see return a future string so I need to save this actual return value within a variable so I will say that I'll create a string variable and then I'm going to say the name for the variable will be V and set it to a weight fetch data and by doing this what's basically going to happen is that now instead of of us being returned a future of string a weight is going to wait for this function to resolve its future and then once that is done the actual return value that we get which is going to be type string is going to be saved within this variable but whenever you're going to be using the aade keyword within a function you have to mark this function as a sync and that's going to fix the issue here as well so with this now I can go ahead and add the print V line again and now you're going going to see that it's going to say future started it's going to wait for this actual future to finish then it's going to save the return value which is going to be string within this variable and then we're going to print that and then print moving ahead so if I click run now you're going to see that we see future started now 2 seconds for the future to resolve then we see future completed and then we see moving ahead so this is the part of async in aade and hopefully now it makes sense to you guys how we use it so the last thing that I'd like to talk about now is that when you're going to be working with asynchronous programming there is a possibility that you're going to be encountering some kind of an error for example the API that you try to reach out isn't available so you're going to get a 500 error maybe a 400 error something like that so how can you work with errors and how can you handle them without making your application crash in the context of asynchronous programming so to demonstrate the TR cat block what I'm going to be doing is going ahead and taking these two statements for fetching the data that we're waiting for and then printing the actual value that we get and I'm going to place them within a TR catch block like so and what a tri catch block allows us to do is that if some code that we write within the tie block errors out that efficiently handle that error within the catch block and not crash our application so when try I'm going to add the same statements again and then within the catch I'm just going to be printing the error and if I go ahead and run this you're going to see that nothing's going to happen everything is going to work the way it was working before and the reason for that is because no errors have occurred but now let's just say that for some reason and I'm going to simulate an error that after the future is resolve I throw an exception maybe this is another error that occurs from somewhere else um something like that and then if I go ahead and click run you're going to see that it prints future started and then it says exception there we go it prints the error the cat block is working because during this operation we had an acception thrown and error thrown you can think of and then because of that the cat block was triggered and then we gracefully handed that error and this is how you can work with error handling within the context of asynchronous programming and then there's also another thing that you can do within the context of a tri catch statement and that is finally and what finally does is that it basically defines them logic that is going to run finally after either the tri catch block has finished its execution successfully or we add an execution the catch block did whatever it had to do and after that finally it's going to be called again so within finally you can basically do some cleanup logic irregardless of the fact whether the actual operation was successful or not or an exception occurred or not so here what I can do is just print uh finally and that's pretty much it and then here I can do print error occurred and then that's pretty much all we had to do so now if I go ahead and I comment out this actual exception and run it you're going to see that we get future started then future completed then finally because the future resolves we print it the finally block is called and then moving ahead and then what I'm going to now do is bring back the execution or the exception again I should say click run and you're going to see that this time is going to say future started then error occurred and now again finally it's going to be called so you can do some kind of a cleanup logic and then moving ahead so with that that's pretty much it in terms of everything that a beginner needs to know when it comes to asynchronous programming in the context of Dart and flutter and the knowledge that I've shared with you in this video is going to pretty much be sufficient enough for you to work with asness programming in 90% of the use cases there might be scenarios where a bit more complicated Concepts might come into play such as isolates or background tasks but you don't have to worry yourself about them at this point try to master the basics for now and once you have a good grasp of them then when the time comes you'll be able to understand and grasp the other more advanced topics such as isolates easily so with that as always if you enjoyed the video then please don't forget to leave a like on the video and subscribe to my channel so that you get notified every time I the de a new video and as always stay happy stay healthy keep learning keep going and I'll see you guys in the next video bye-bye
Info
Channel: Hussain Mustafa
Views: 1,130
Rating: undefined out of 5
Keywords: flutter, flutter async await, dart, flutter tutorial, get started with flutter, how flutter works, dart asynchronous programming, dart async await, dart async, dart future, dart future async await, flutter asynchronous programming, asynchronous flutter, futures flutter, flutter networking, flutter async await future, flutter programming, dart programming language, flutter beginner tutorial, dart beginner tutorial, dart isolate, dart language, async, await, flutter in focus
Id: PCOpZMHEZNc
Channel Id: undefined
Length: 19min 30sec (1170 seconds)
Published: Wed Jun 26 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.