#14 - Dart Control Flow Statements - if/else, for, while, switch, throw, catch + ENUMS & EXCEPTIONS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what is going on everyone i'm wicked welcome back to my dart from novice to expert complete course i hope you're having a great day in this tutorial we're going to hop on the flatterly train and move over to the next important station of our dart language tour and that is dart control flow statements so without further ado let's get right into it beforehand though i want to send a token of appreciation to everyone supporting me as official youtube members especially to diana and michael aka aza on discord if you want to become a member all you have to do is to click the join button right next to my channel and pick your desired membership having that said let's continue with our tutorial now in order to talk about control flow statements we first need to see what i mean by saying the flow of an application so we learned from previous tutorials that whenever you run a dart application it will start its execution process inside the main function therefore the flow starts right in here and it will advance line by line to the next step the best way to visualize this flow is to add a breakpoint right at the start of the main file and run the application in debug mode by hitting the f5 keyboard shortcut you will be able to follow the flow of an application by simply watching this arrow right here you can advance to the next step by clicking these buttons or by hitting f10 f11 or f12 the step in f11 shortcut will get you to absolutely each line of the execution flow including functions and nested functions literally every line of code if you'd like to skip the path inside functions you can use the step over f10 shortcut to progress and if you are already inside a function call and you want to exit you can press the step out f12 shortcut so you saw the execution flow of our current basic application but the thing is that this tutorial is named control flow statements right therefore there must be some statements that can modify that can control the way the flow goes from one line to another for example if we use an if statement then depending on the value of the boolean expression inside of it one of the paths here will remain unexplored into the execution flow right or if we use a for loop then the code inside the statement will be repeated in the flow of the application so that instead of writing five print statements one after another we can write only one and tell the flow to repeat it having this in mind here are the statements that you can use in order to control the flow of a dart application starting from the if and else statement i'll tell you everything you need to know about each of the available control flow statements bear in mind that try catch and throw statements since they can raise exceptions and thus stop the flow of a program are also control flow statements and we'll also discuss them inside this tutorial first and foremost let's talk a little bit about the if and else statements now i know many of you already know mostly everything about if else statements and their syntax however i need to remind you four important things about them firstly and probably one of the most time-saving quick tips i could give you is that instead of manually writing the if and else statement just like this you can use the already existing dart snippets as you can see if we type in if you have two snippets emerging as autocomplete options the first one will generate the simple if statement and the second one will generate the if plus else statements secondly having what i said in mind you can deduce that the else statement is optional so you don't need to write an if else combined statement you can only write an if and do something only if the expression inside of it is true thirdly i need to remind you from the tutorial on dark built-in types that the expression inside of an if or else statement must always evaluate into a boolean value they can either be true or false nothing else is accepted as a condition inside of these statements last but not least as we have already seen in the previous tutorial the usual if an else statement can be written as a conditional expression this time take in mind that the else statement is also obligatory so you can turn a long statement like this into something pretty neat just like this and i think this is pretty much everything you need to know about if and statements in dart it's time to move over to what's probably the most popular statement you'll use when deciding to iterate or to loop through something in dart and that is the for loop so in order to iterate through something let's create a list of integers containing values from 1 to 5. just as before dark comes with some really handy for loop snippets so that instead of wasting a lot of time manually writing their syntaxes you can simply use the default for snippet or the for in one now the difference between these two approaches is that in the default one you can also access the value of the index inside the iteration in the case of the for in approach the item variable is actually being assigned to each value of the collection from inside the iteration having this in mind we can deduce that the default for loop approach is more robust and can be used with iterations inside of which you care about the iterating index and you can even change the iteration index to increment in a different manner perhaps if you just want to directly iterate through an iterable collection from start to finish and you don't care about the current iteration counter you'd be better off using the for in form of iteration and speaking about iterables you know from the tutorial on dart functions that every iterable class benefits from a quick for each method that can iterate to every item inside a collection really fast while it can take an anonymous function as a parameter in order to have access to each item if you just want to print the values you can directly send the print function as a parameter by using its name if this seems strange to you make sure you revisit my tutorial on dart functions as it's really important to understand these concepts alongside for loops dart also supports while and do while loops and it also comes packed with their useful snippets basically the only difference between them is that the while loop evaluates the condition at first to check if it can still proceed looping do while on the other hand evaluates the condition after each loop to see if the next loop can still be executed so the do-while will obligatory do a loop at first no matter the condition is before it does the first condition check from my experience i have rarely used the do wild syntax it's always a matter of condition tweaking to convert from a do while to the simple while loop so it's not worth the hassle to use both of them at least in my perspective note that due to their syntax while and do while make us infinite loops if the condition never changes to something that evaluates into false so take that in mind and since we're talking about this you may ask yourselves are there any ways on how we can directly interrupt the execution of a loop while being inside that loop let's take our previous for loop example i want to exit the loop whenever i'll find a value of 3 inside the list so what i could do is use an if statement and if i find a value of 3 i could set the iterator value so that for the next iteration it will exit the loop while this is completely fine you have to agree with me it looks absolutely terrible there is a much cleaner way on how you can interrupt the execution of a loop and that is by using the break statement wherever you want to cut the loop execution just drop in a break statement just like this and now as you can see it works the same as before but not only that but it also looks seamless break statements can be used inside any four while and do while loops in order to prematurely stop them from running having talked about this you may ask well if we can use break to completely stop the loop is there any softer way on how we can skip only one iteration and move to the next one inside a loop for example is there any way on how we can skip printing the value of 1 from our list for loop yes it is we can write if item equals 1 then continue the continue statement will end up the current iteration and move to the next one inside the loop of course you could have written if item is not 1 then print the values which would seem a more logical thing to do but for learning purposes i showed you how you can do this by using the continue control flow statement there is even a much cleaner way to do it by using some list collection functions like where and for each to filter the items we want to print then print them as we have previously seen now you must agree with me this looks better than using any four iterations and this is the beauty of dart everything can be written in such a minimalist manner now having all this said it's time to move over to a really really interesting and important control flow statement the switch case statement at first you should know that the switch case statement was designed to be kinda limited from a coding perspective and as much as you think this is a bad idea limiting stuff to work only on certain specific cases brings more stability into the game again there is an implicit dart snippet for it so make sure you use it every time you'd want to create a switch statement so you should think of a switch case statement as being more like a stripped down version of an if else statement say we have a switch case written like this this as hard as it may seem to believe is equivalent to writing this if else statement however that's pretty much everything you can do with a switch case use it as an if else statement comparing a default single input value to a set of multiple other values the limitations continue even further since switch statements in dark can compare only integers strings or compile time constants using the equal equal operator as we learned in the previous tutorial in dart the only variables that are equal by default are those pointing to the same reference object in the memory and variables pointing to the same objects in memory must always contain compile time constant objects remember integer and string objects hold constant values so it's absolutely facile for the switch statement to compare their values by using the equal equal operator since this operator will actually call the identical method on the values making sure they point to the same constant object in memory another condition is that the class from inside the object you want to compare must not override the equal equal operator so that dart makes sure you won't be able to alter the comparing process the difference between identical and equal equal operator was covered in the previous tutorial so i invite you to watch that it will definitely make more sense now even though switch case statements only work with integer string and compile time constants 99 of the time you'll find them being used with another type we haven't discussed yet because i wanted to wait in order to introduce it in this specific context i'm talking about enumerated types or enums as everyone calls them there's not much to say about enums they look like this you can declare them by using the enum keyword what an enum basically is is a special class used to represent a fixed number of constant values so for example in my case i have a weather conditions enum containing all types of constant conditions the weather can have like sunny cloudy foggy rainy etc they're not going to change most of the time we'll use enums containing constant values just like these and why do we do this well because when comparing to objects especially of type string it's so easy to mistype a letter of one of the strings and your program will go haywire really fast so to prevent this from happening we use enums to encapsulate the specific value into a class and access it directly like it was a static field just like this now all we need is to create a variable holding one of these class values note that the enum class cannot be instantiated it only exists through all of its possible values inside of it coming back to our switch case statement you can see it became really really neat and organized it isn't prone to string errors anymore so let's talk a little bit more about these cases these are called case clauses and they can be either non-empty as we have them here and empty as we'll see in the following minutes but first let's focus on these non-empty fields as you can see by default non-empty case clauses require a break continue throw or return statement at the end since whenever dart finds two equal values it's time for it to exit the switch statement it can either do it by exiting it directly by a break throw or return statement or by passing this job to another case clause by using the continue statement and a label just like this using a continue statement may be used when you want to do something in response to two values for example in our case in case it's drizzling outside i would like to print both that it's drizzling and raining by using the continue statement just like this on the other hand in case of empty cases you don't need any of these break return throw or continue statements but take in mind that if you have something like this it will act just like before as a form of fall through this time for both when it's drizzling or raining it will only print that it's raining since it will fall from the condition that grizzly to condition that rainy and it will exit the condition there from the break statement also you can notice that there is a default case at the end denoting the flow our app will take if there have not been found any cases for this input right here however in the case of an enum you don't have to mention it since you can't have any other values as an input here and at the same time dart will show you a warning if you want to write cases for all of your enums fields and i think this was pretty much everything you need to know and learn about switch case statements and enums time to move onto the assert statement the assert statement is one of the easiest statements to understand it is used to disrupt the normal flow of a running app if the boolean condition inside of it is false so for example you might want to stop the program if this list is empty when it reaches the assert statement so what you want for the app to keep running past this point is to have this list variable not containing an empty list therefore we'll write assert and the condition will be list that is not empty and we can also pass a second argument containing the message that will be displayed if the condition will be false now a really important characteristic of an assert statement is that there are only present in the code when running it in debug mode when running it into production mode without debugging all asserts inside your code will be removed and the program will run completely fine even though the condition will be evaluated to false therefore asserts are mainly a tool that can aid the development workflow a little bit more by double checking some important conditions and having this said we have only one more topic to cover before we end up this tutorial and that is exceptions especially the throw catch and finally control flow statements exceptions such a beautiful and dangerous topic to be discussed so you must be pretty much aware that there are some places in your dart code when something unexpected can happen something that can cause your app to terminate if something bad happens an exception is true now the dangerous thing about exceptions is that when they get thrown if they aren't caught somewhere along the freefalling then the program gets terminated in short it crashes and if your app crashes users will be mad and if users are mad they'll give you bad ratings and the chain of horrendous things will continue the road starting from when an exception is shown to when your reputation as an app developer begins to drop is really short so you'd better catch those exceptions until it's too late think of an exception inside an app like throwing a ball from the 20th floor of a building when the ball touches the ground the game will be over and this literally happens in a matter of milliseconds inside the program so what you should do is to have some catch statements along the way that can literally be more like some nets catching the ball from falling at a lower level when an exception is caught the program won't crash anymore and you even have some ability to fix the problem by using the final statement finally is more like an ultimate step on how you can fix your unexpected error so let's see everything we learn into practice in the following minutes say for example we have a variable called zero that must not contain anything apart from the value of 0 when it's going to have a value bigger than 0 we'll throw an exception when it's going to have a value less than 0 will throw another exception now in dart as expected exceptions are well objects object instantiated from the exception class which is actually a built-in type similar to exceptions dart also has an error type which pretty much acts the same as exceptions a production quality code will always throw types or classes that implement either this error or these exception classes as you can see inside the error class for example dart devs have already created some errors that will be thrown in some dangerous situations similar to how they implemented their own specific exceptions and errors this is how we can actually implement our own so all we need to do is to create two exceptions i will call them positive value and negative value both classes will implement the exception class and don't worry if you don't know what the implement keyword does for now we'll learn everything about classes in the following two tutorials as you can see every exception must have a message so we're going to set a final field like that and set it into the constructor of both classes now we have an utilitarian from inside the math library that can generate two numbers between a range of numbers in our case this line of code will generate an integer number between -1 and 1 so a random value between -1 0 and 1. we want to detect if our variable got an unexpected value so we're going to surround our next code in a try catch block as you can see by using the already baked in dar snippet inside of this we'll test the possible problems that may arise and those are whether our zero variable is less or greater than zero in either of these cases we'll throw the corresponding exception so this is the moment where the ball starts dropping from the 20th floor so we need to catch it before it's too late we can do that in two ways we either use the own keyword followed by the exact specific type of exception and if it matches it will catch it and enter its scope just like we did with the negative exception however know that in this case if you don't treat any possible exceptions that may arise they won't match any of your options here and it will eventually end up not caught and scratching the program and this is why it's recommended that we use the catch statement that will literally catch all types of thrown exceptions inside of the catch scope you can check whether the type of the code expression is of one of our expression types and if it is proceed like we did above by printing a specific message and as a final step after we catch the exception we can use the final statement to set the zero variable to hold the correct zero value if we run the program right now we'll see which ones of the expressions will get thrown and caught and how the flow of the application will progress during all these steps one thing left to be mentioned is that after catching an expression you can also rethrow it in order to be catched later on with another catch statement this is like playing with fire and rethrowing the ball after you caught it on a lower level so that another person with a net will catch it from a more inferior level i hope you understood how exceptions work inside dark and how the try catch and final statements can control the execution flow of an app having that said it is finally time to end this tutorial on dart control flow statements i hope you understood them in great detail in the next tutorial as i previously said we'll move over to the next station of this dart language tour in which we'll start discussing everything we need to know about classes in dark as always if you like this tutorial don't forget to smash that like button subscribe to my channel and share the video with all of your friends and colleagues in pursuit of top tier development until next time as always take care wikis out bye bye
Info
Channel: Flutterly
Views: 1,150
Rating: undefined out of 5
Keywords: dart, dart tutorial, dart course, dart complete course, dart control flow statements, dart execution flow, dart flow, dart if, dart else, dart for loop, dart for, dart while loop, dart do while loop, dart switch, dart switch case, dart throw, dart catch, dart try, dart exceptions, dart enums
Id: uVo1nDySzO4
Channel Id: undefined
Length: 23min 21sec (1401 seconds)
Published: Thu Jul 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.