#11 - Dart Built-in Types - num, int, double, String, List, Set, Map & Runes

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 in this tutorial we're going to hop on that flatterly train and arrive at the next important station of our dart language tour and that is darth's built-in types 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 in the last tutorial we saw a bunch of examples on how to declare dart variables right we understood that we can declare a variable like string s equals hello int a equals five list of integers l equals one two three and we also learn that the value a variable is assigned to is actually an object an instance of a class denoting the type of the variable but this way of creating an object is pretty unusual right i mean we're used to creating an instance of a class by writing something like this or perhaps something like this right so why does dart allow us to instantiate basic objects like integers and strings by using a faster approach well because dart is thinking of optimizing stuff as much as possible both in terms of performance and ease of writing code that's why it added the special support for these types so that you can easily create objects by using literals for example the hello is a string literal from which dart knows how to create a string object 5 is an integer literal from which an integer object can be created and having in mind what we discussed in the previous tutorial we know that these literals are actually constant values so perhaps if you're typing in 20 integer variables having all the same value of 5 there won't be 20 integer objects created on the memory but rather only one constant integer with all variables pointing or holding a reference to it i think you got the idea on how dart optimizes this kind of stuff next up it's time to see all the built-in types dart language has special support for but one may ask what exactly are built-in types are there any other kinds of types we should expect let's answer these questions one at a time built-in types are well the default types you'll find inside dart sdk score folder as you can see if i hold ctrl click on the integer type it will get me right into the location where the integer class was implemented and we can observe that this file is located inside the core folder which is also located inside the lib folder as a result we can clearly state that these are actually the core libraries of dart inside of these libraries you'll find most of the built-in types we'll discuss today and they are called built-ins because they come by default pre-baked in every dart package you don't have to import any core libraries in order to declare an integer right are there any other kinds of types definitely by using specific libraries like math or collections you have access to more advanced types like point rectangle hash map and q in this tutorial however will only focus on built-in types so here's a list of the entire built-in types you can find inside dart we'll briefly discuss the majority of them in this tutorial over the last tutorials we've actually talked about some of these built-in types null object never and dynamic are not strange to us anymore and you probably know that the void type indicates that a value is never used however types like future stream and iterable will have their dedicated tutorials later on this course having that said let's go ahead and dive into the numbers type now a really important aspect to be noted is that the class your key containing the number class looks like this the number class is minimally named num as you can see both integer and double are subclasses of the num class meaning that both integer and double are subtypes of num type this from an object-oriented aspect means a couple of things first and foremost in and double are in fact numbers meaning that the methods from inside the num class are completely accessible to both int and double types secondly int and double are special enough to re-implement some of nums existing methods by perhaps bringing some abstraction and extra functionalities to the base num class and thirdly the num class or should i say type can host both integer and double values it's like a hybrid between these two and the operators and methods from inside of it will work at the same time on both integer and double types having these in mind let's move over to some practical examples note that by following the effective dart rules local variables should be declared by using the var keyword however i deactivated this rule inside my analysis options.yaml file so that you'll be able to see the types i'm declaring more clearly now basically we all know what integers are they hold numbers without a decimal point right we can declare an integer a by assigning it an integer literal on the other hand if a number includes a decimal then it is a double nothing new until now so as expected we can add we can multiply we can subtract our integer with another integer and our double with another double however if we try and add our integer with a double we can observe it's actually possible to do it why is it possible because at the end of the day they're both numbers and the arithmetic operators are defined inside the base num class but then you might ask why is there a separate integer and double types if num can handle all the operations with ease well the reality is a little bit different if i declare a num variable and assign it to an integer value everything is correct until now right well can you tell me whether it's odd or even yes you can but can dart tell me whether it's odd or even no because that would mean the noun class would need to have the two methods called is odd and is even right inside of it and what would prevent num not to implement that well num class accepts both integers and double values now can you tell me whether a double is odd or even no because this question is only available for integers so you see this is why we also need to have two separate types for integer and doubles so to sum up you can declare a variable of type num whenever you want to use the functionalities that can be applied on both integer and double values not to mention that obviously if you declare a variable of type num then that variable can switch between integer and double values during the entire execution of your program whereas when you declare it as an integer well it won't be able to hold integer values for the rest of its time to shift the discussion a little bit there are some important functions you need to extract from these classes that are really useful you'll find yourself having to know these methods quite often during your development phase for example if you have a string and you want to quickly turn it into a num integer or double you can use the parse method just like this vice versa if you'd like to convert a number integer or double into a string you can use the two string method another interesting method that works on nums and that means on both integer and double variables is the clamp method clamp will be called on a value and it will project that between a lower and an upper value this is useful when you have multiple incoming values that need to be set between two specific numbers other useful methods are the seal floor and round trio all of them work on num variables however they're only useful on double values and you'll realize that after we see what they're all about the seal method returns the nearest integer that's not smaller than your current value the floor method returns the nearest integer that's not bigger than your current value and the round method simply returns the nearest integer without any other restriction so as you can see all of them return integer values so if you were to find the nearest integer that's not smaller than your value for an integer value instead of a double well logically the result will be the same integer value and so is the result for the floor and round methods as well so that's why they're only useful on double values also you need to take in mind that the default division operator returns a double value therefore if we divide 3 by 2 we'll get exactly 1.5 and not 1 as you might be used to if you'd want to receive only the trunked value of the result which in our case is 1 you need to use the truncating division operator which is the default operator prefixed by a tilde symbol note that with the default division operator since it returns a double if you divide by zero you can escape from retrieving a division by zero exception since double types accept infinity and not a number values and that's what the result of that division will be however if you use the truncating division operator and divide by 0 an exception will be thrown since the integer type does not support neither infinity or non values another quick thing to be noted is that all num integer and double literals are constant values we also need to talk a little bit about operators in these number sections especially about the plus plus minus minus plus equal minus equal but i'll make sure to cover them in a separate video dedicated to all operators so i think this showed you pretty much all you needed to know about numbers in dart therefore let's move over to discussing the string type now strings similar to numbers are some of the most frequently used types in dart language and especially in flutter framework everywhere you look there will be a string displaying a text and most of the time you'll find the string literals interpolating different expression values strings at their course are a list of code units or characters this hello string is actually a list of 5 elements or should i say characters and you can access its content individually by using the list access operator just like this one way to create a string object is by using single quotes another way you can do it is by using double quotes double quotes are especially useful when you'd have a string containing single quotes that need to be contained in the actual string just like this however you can escape the string delimiter even in a single quote scenario by proceeding with a backslash the quote you want to include in the string just like in this example now we previously talked about interpolation in dart you can interpolate identifiers and expressions within the string content in case of a single identifier you can interpolate it by preceding it with a dollar sign what the dollar sign actually does is call the tostring method and concatenate the response within the existing string however a really nice feature is that you can also interpolate expression values and you can do that by wrapping up the expression with curly braces just like this what actually happens under the hood is dart evaluating the entire expression at first retrieving its value then calling the tostring method on the value and concatenating the response within the existing string all of these just by using this simple syntax we should also talk about string concatenation now and how you can display a string on multiple lines so you can concatenate two strings really really easy by using string literals one after another or if you want to use identifiers by using the plus operator just like this but what if you want to display this piece of string on another line how do you signal this to dart well you can do it in two ways the first option would be to use the backslash and delimiter this way whatever is after the delimiter will be set on a new line the second option would be to create a multi-line string this can be done by using a triple quote with either single or double quotation marks so that dart will literally take into consideration all break lines in between by default and display the string appropriately however one may ask well what if i literally want to display the backslash n combination in a string is it possible and yes it is you can always create an absolute pure string that will display everything inside of it by prefixing it with r just like i showed you in the example on the screen right now one more thing to be noted about strings is that you can also express unicode codes by using the backslash u delimiter however we'll talk more about this a little bit later in this tutorial when we'll get to the runs type and in order to end this topic related to the string built-in type you have to know that literal strings are constant values of course as long as any interpolated expression will end up evaluating in a constant value i think this sums up pretty much all you need to know about strings for now of course we'll talk about all of its particularities like methods and regular expressions more in depth in future tutorials but for now the foundation is what you should be focused on moving on to the next built-in type the boolean type is definitely the easiest to understand but at the same time it plays a really important role in dart and you'll find yourself using it many many times this is because only two predefined objects can be of type buu and those are as you guessed it the boolean literals true and false they can be used to denote truth and both are constant values however you'll often find methods and expressions that evaluate to a boolean value which is either false or true to deviate from the subject a little bit for understanding purposes the if statement itself actually works by accepting only expressions that will end up evaluating into boolean values therefore it is completely legal to say if b when b is a boolean variable since b can evaluate only in either true or false this is actually equal to writing if b equals equals true or it is legal to say if 3 is greater than 2 since this operator defined expression returns a boolean value this is equal to writing if 3 is greater than 2 equals equals true however you can't for example write if a when a is an integer just to check if a is not 0 or you can't write if name when name is a string just to check if the string is not empty you can't even check if passenger when passenger is a new level type just to check if the passenger is not nu if statements only work with expressions that can certainly evaluate into a boolean so for the integer you could write if a is not equal 0 for the string you could write if name is not empty and for the null you can simply write if passenger is different than no because all of these evaluate into boolean values they're either true or false i hope this pretty much sums up everything you need to know about boolean types for now we'll get to them back into discussion once more when we'll tackle the dart operator subject later on this course it's time to move on to one of the most crucial types in dart lists lists are perhaps the most common collection in every programming language and in dart they denote an order group of objects if we go ahead and check the list class you can observe it extend some kind of an iterable class which surprisingly or not it's also a type now iterable is definitely something that we'll discuss later on since it's related to synchronous and asynchronous generators but what you need to know for now about an iterable object is that it is mainly a collection of elements that can be well iterated traverse a list can be iterated so that's why it extends iterable dart lists use 0 based indexing meaning that 0 is the index of the first value and list at length -1 is the index of the last value so at first being an ordered group of objects this shows us that a list is a generic type meaning it can contain objects of multiple types well yeah if we go ahead and check out its class implementation we can see from this universal type between angle brackets that it works with different types therefore for example we have previously seen that we could create a list of integers holding integer values or that we could create a list of booleans holding true or false values and since all of these types are actually classes that can be actually instantiated into objects we can have a list of our class a specifically containing object instantiated from that class the possibilities are endless but the real question now is can a list contain objects of different types for example can we have a list containing an integer and a double well the answer is yes we can do that in two ways by using object-oriented programming concepts or as we learned in the previous tutorial by using the dynamic keyword which is going to set all types accordingly at runtime we have actually seen the first approach already in today's tutorial we learned that both integer and double are subtypes of the base type called num therefore a type that can both represent these objects inside the list is none so we could set the type of list as being a num but what if we want a string literal too and a boolean literal well in this case we need to somehow find the type that is further at the top of the type tree and that can represent each and every one of them we learned from the tutorial on null safety that the non-nullable top type is object so we could set the type of the list as being an object if it contains non-nullable values but what if we want a list to hold a null object also well in that case we also learn that if we want the mother of every type in dart including null we should use the nullable object question mark type because this type can literally represent any other type in dart now since our list holds a variety of different objects it's absolutely our duty to make sure we properly cast them back to their right type in order to access their appropriate methods you can see we can cast to a real type by using the as keyword what we also need to know is that we need to take double caution steps due to no safety since a list can be non-nullable and contain non-nullable objects inside of it a list can be non-nullable but can contain nullable objects inside of it a list can be nullable and contain non-nullable type objects inside of it and a list can be knowable but can also contain nullable type objects inside of it and now while we're here why don't we have a look at the basic ways on how to create a list object and assign it to a value in dart because there are some important key factors you need to take into consideration you can't create a list object anymore by using the default list constructor this constructor was used to generate a list of a set length value by assigning all values inside of it with no and you might realize that in null safety this would have been a huge threat therefore the default list constructor is completely deprecated and shouldn't be used as an alternative you can use the trustly list literals containing anything or even an empty list or you can use other specific constructors like list.field dot empty dot from or dot generate note that some of these methods have a boolean growable field a global list means that the list length can grow after declaration so it's up to you if you want that or not the list literals are growable by default lists are such a huge topic to cover and i won't be able to do this in detail in today's video since it will literally take me ages however here some of the most important features arising from lists and collections in general dart uses what's called a spread operator denoted by three consecutive dots and the null aware spread operator denoted by the same three consecutive dots followed by a question mark to provide a really efficient way to insert multiple values into a collection but wait wait wicked you barely introduced us to the single dot and then you're telling us about three consecutive dots what about two consecutive dots is that even a thing in dirt and yes fortunately it is and since you asked for it let me give you a quick overview of all the dots i know it's not really related to dart built-in types but they are really useful to know when talking about lists collections and objects in general we'll start with the dot operator and the null aware dot operator you can use this dot operator on an object to access class fields and methods you must already know this from other programming languages it's pretty basic stuff the nullaware.operator precedes the dot with a question mark and makes sure to always access the fields or methods only when the caller is not known it's like writing a condition if something is not null then call the function on that you should however not mix this up with the exclamation mark followed by a dot the latter forces dart to call the method no matter what and it is used when the analyzer is in doubt that the value you're calling it on may be no but you're 100 sure it isn't let's continue with the cascade operator and the null aware cascade operator this operator as its name implies is used to call multiple methods or fields on an object just like a cascade one after another what do i mean by that let's say we have a list equals 1 0 2 for example we want to sort this list to reverse it to add the content of another list to it then to sort it again then perhaps i want to add one to each of the elements sort them again and then print the list if you have to do this normally you'd simply call all these methods one after another line after line right well you can do this in a much simpler way by using the cascade operator and place all methods one after the other one just like this however note one really really important difference in the first example our list at the end contained the correct 1 to 6 values in the cascade alternative however we ended up with values from 0 to 5. can you look at both approaches and notice where the error is if you set at the map function you were definitely right you see the sort and add all methods are functions returning void this means in this case that they're mutating the object they're calling the methods with directly on the go our list is getting changed on the fly however the map method generates an iterable from our list by applying the changes to each element so we actually need to assign the new value to our list just as we did in the normal example not only that but we also need to convert it to a list by using the to list method since as we said by default the map returns an iterable object so in our case when using the cascade operator we're just creating the list but we ain't assigning it to anything therefore losing it the thing is that whenever you see methods that will return something that needs to be reassigned to your object you need to use the default.operator and use the already existing assignment process to do the job but as we can see the analyzer screams that we can't call the map method on void and that's completely true because we don't want to call it on the add all method but rather on the entire generated list until now and how can we do that well we must surround the current generated list with parentheses and call the map method on the parenthesis instead what we're essentially doing here is creating a temporary list then calling the map on that list generating an iterable then we can call the to-list method to switch back to it as being a list again and then after all we're finally assigning the temporary list to our variable if we print the list we'll see that the lists are indeed identical now and voila i hope you understood in big words how you can use the cascade operator efficiently i guess the null aware cascade operator's job is self-explanatory by now finally we need to talk about the spread operator and also the null aware spread operator notice that the null aware spread operator compared to the previous two had its question mark placed at the end only god and dardev's know why that is i guess it just looks better compared to the previous two so for example if we have three lists and you want to quickly insert all values from the first two of them to the last one you can use the spread operator just like this this is equivalent to writing list3 dot dot add all list 2 dot dot add all list 1 and speaking on the null aware spread operator as we saw before it happens that the list you want to insert can be no well in that case we need to make sure it won't get inserted into our list so we post fix the spread operator with a question mark and finally we're moving on another great feature dart offers for lists are collection if and collection 4 which you can use to build the content from inside of them using conditionals and repetition let's say we have a list containing the menu of a website we want the offers tab to show up only when the sales active boolean is true so we can easily do this by using the collection if syntax and perhaps if you have more than one tab to add in the menu you can use the collection for syntax similarly just like this as you can see we can actually link them together and create some really interesting logic right inside the constructor of a list how amazing is that and so that i won't forget compared to numbers strings and booleans list literals are not constant by default however you can make them compile time constants by preceding them with the const keyword as we have learned in the previous tutorial the list type has many handy methods for manipulating and creating lists however as i said these will be covered up in detail later on this course for now i think you get the idea on how lists work it's time to move on to another collection type sets are actually pretty similar to lists to some extent however they come with two major differences while lists as we saw were ordered and could contain multiple identical values inside sets are unordered collections of unique items so if we create an empty list and add four values inside of it as you can see even though two of them were the same they've been added without hesitation what's worth noting is the order is actually the same as we coded them if we tried the same sequence for an empty set you can see you will end up with only three values since two of them were identical and what's also worth mentioning is that the order on how we added them still persisted that's indeed the case in this scenario but i can guarantee the order won't always be the same with other types of sets because we simply don't have any access operator like we had in the case of lists now a really important thing to be noted is what are the basic ways on how you can create a set well similarly to the basic ways on how you can create a list a set is also a generic type so the way we create it will be pretty similar however there are some subtle differences you need to take in mind firstly compared to lists you can create a set by using the default set constructor since this actually creates just an empty set with no values in it secondly you can create it by explicitly mentioning its type and its generic type with or without an empty set literal thirdly you can create it by using var to infer the type but you must assign it to a non-empty set literal last but not least you can create it by using var to infer the type with an empty set literal but with its specific type annotating it so then you might wonder why can't we declare it by typing var set equals the curly brackets in the case of this we could do that why isn't it possible here and let's find out why what happens when we type in var set equals curly braces well we can notice that the set identifier was set to a type of map instead of a type of set why does this happen in dart the syntax for map literals is quite identical to the one for the set lead roles the thing is that map literals came first were developed first therefore the curly bracelets alone defaults to the map type so in order to set the type to a set we need to help the analyzer by giving him some hints that we want a set instead of a map and we saw those scenes in the examples before apart from that a set is pretty much identical to a list i mean you can still add elements to the set by using the add method or multiple elements from another iterable sequences by using the add all function sets also support spread operators and collection if and force just like lists do and similar to lists in order to create a set that's a compile time constant we use constant before the set literal but then one may ask are sets all that useful compared to lists well they really are because you can intersect them with other sets join them with other sets calculate the union between two sets etc you know this kind of mathematical operations you learned on sets can be really useful for specific tasks and having all of this said it's time to move on to the map type since we previously brought it into discussion even though they have the same literal syntax as sets maps don't really look anything like sets in dart a map is an object that associates keys and values both keys and values can be any type of object therefore maps compared to lists and sets don't have only one type between angle brackets but rather two one for the type of the key and one for the type of the value each key must be unique and occurs only once but you can use the same value multiple times if you're familiar with json well this is exactly what a map is in dark there are several ways on how you can create a map object and assign it to a map variable firstly compared to a set you can actually declare a map by directly writing var map equals the curly braces since as we've discussed this is the default literal for maps secondly you can do it by assigning a variable to a map literal and then by manually inputting its keys and values know that you can assign a key to a value by using the colon operator thirdly you can do it by using the default map constructor since compared to the default list constructor all it does is create an empty map then you can easily assign specific keys to their values now having this said we have a couple more things to discuss since this is a key value collection what is it going to happen if you want to access a key that isn't in a map well that will return no therefore in order to avoid any null exceptions that may arise when calling something on a null value the map index operator is nullable it's required that you use the exclamation mark to denote that you're 100 sure the value you're retrieving is safe to call other fields or methods another thing you need to know is that similar to lists and sets you can also add entries to a map even after you declare it by using the add entry method just like i'm showing you on the screen right now maps also support spread operators and collection if n4 just like list and set do you might not realize it now but i can tell you from experience you're going to use maps a lot during your development workflow since they're basically the go-to option on how to store perhaps a retrieve json from an api and having this said i think this sums up everything you need to know about maps at least for now it's finally time to move on to a not so well-known dart built-in type have you ever heard about the runes type if not stay tuned because we're going to cover it right now basically runes are a collection formed out of all unicode decimal code points of a string a code point is an integer value that uniquely identifies a given unicode character from inside a string what i haven't told you when we talked about strings was that a dar string is a sequence of utf-16 code units a code unit is the unit of storage of an encoded code point utf-16 means that the code point of a unicode character has been encoded to a 16 bits code unit then the code point is a hexadecimal number what this basically means is that in dart every string is split between characters and each of these characters has a hexadecimal code point behind the scenes in dart a string is no more than a list of these hexadecimal code points so if we create a variable and link it to a runes object with a hello string if we print it we'll actually see the utf-16 code points of that string however converted into a decimal code point in order to see its hexadecimal values we can call this method and set the 16 bit as a base then pad it to the left so that it will always be 4 characters long and in order to call it on all elements from inside the rules list we can use the map method if we print this you can see these are the unicodes for each of our characters inside our string what's even more amazing is that dart offers a way on how to interpolate these unicodes inside a string by using the backslash u delimiter with the help of curly braces so instead of writing hello we can actually write this sequence of unicode codes and if we print this string we can actually see it prints the exact same string as before well after having this said you might say that you won't be ever using this and yeah you might be 100 right about that however it's a really nice thing that you know and understand how strings work in dart and how you can manually input any hexadecimal unicode code point you'll find on the internet and that's including emojis directly into your string so have fun experimenting and testing what you can create with dart it is finally time to end this long tutorial on dart built-in types i hope you have at least a strong foundation on how to start using all of them in the next tutorial we'll move over to the next station on this dart language tour and that is the dart function station in which we'll learn everything about functions parameters and return types 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 wicked is out bye bye
Info
Channel: Flutterly
Views: 1,769
Rating: undefined out of 5
Keywords:
Id: fXMX7frTKIA
Channel Id: undefined
Length: 39min 53sec (2393 seconds)
Published: Mon Jul 05 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.