Built Value Tutorial for Dart & Flutter

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Instead of providing such packages the functionality should be part of the language

👍︎︎ 1 👤︎︎ u/MikeMitterer 📅︎︎ Jan 23 2019 🗫︎ replies
Captions
data classes immutability simple serialization this is what dart does not offer right off the bat while dart is surely one of the better languages with regards to its simplicity it just currently lags the support for value types when you compare two objects of the same type with identical contents they will still turn out to be not equal by default Dhar checks for a referential equality not value equality making a copy of an object is also painful you have to write so much code and serialization well don't even mention that because there is even more repetitive code for you to write but not with built value library it will save you so much time by allowing you to write a good quality code without all the repetition hello welcome to resew coder this is the library that you are going to learn about in this tutorial currently it's at version 6.2 point now but this tutorial should work even with more up-to-date versions because at this point this library build value is just so mature that there should not be any breaking changes down the road let's now go into vs code and let's add this build value library over to our project so in the pub spec IMO file we are going to add a dependency which will be the build value this is simply copied from the library's page and then also build value depends on built value generator which depends on build runners so we are going to add them under dev dependencies so yeah build value generates some code for you so that you don't have to write it by hand when we press save it's going to these packages are gonna be gotten and now I am using flutter in this tutorial but build value is just pure dart library so you don't need to use flutter but just for simplicity because I think that most people who are using dart are using it because of flutter so that's why we are in here however we are basically not going to touch flour in this tutorial at all we are going to be working only with console output the only thing that we are going to be doing with flour in this tutorial is that we are going to again remove all of the comments so ctrl F then search for slash slash dot and asterisk enable reg X and where we want to replace all comments with blank space now formatting saved then because we don't want to be dealing with flour we are going to delete this counter because we don't need it we are going to delete this whole body element of the scaffold so you are going to be left only with the app bar and also the floating action button and this unpressed property of our floating action button will call our function which will be simply avoid run code it's going to be private so we want to run code here so this will be called from the unpressed in floating action button so whenever we press the button our code will run and the console output will be shown in our debug console right over here so unpressed will call run code and also you can get this full code from the link in the video description if you don't want to type this all out and then because we don't just want to type our code into this my home page state class we're going to create a separate class called code runner right under the lip folders so let's create a new dart file called Runner and this file will contain only one simple class code runner and it will have a static void run code this is where our code will be written so now inside the main dart file inside run code we are going to simply call code Runner the run code and also import code runner over here and now we are good to go so we can move towards the build value alright so it probably wouldn't be a bad idea to create some build value right now we are going to create a class representing a vehicle and we are going to call built vehicles so let's create a new file for that under the lip folder actually not directly under lit folder but let's organize our code a bit so we are first going to create a model folder and inside this model folder we are going to put our built vehicle dot dart built values are abstract classes our will be named built vehicle and they have to implement from built and inside the builds type parameters we are going to first specify the built vehicle class so just copy and paste that here and then built vehicle builder this built vehicle builder will be generated for us by the code generation of the built value code generator this code generator brings me to another point and that is that you need to specify a part for this file because this built vehicle dart file doesn't at all make sense on its own it needs to be a part of something else and it will be part of the generated code which will be under built vehicle that G for generated dot dart it will make sense in just a little while when this code will be actually generated then our build vehicle will have some fields or properties so string get brand it needs to be a getter only that's because build values are immutable we're going to add more properties later just for now let's move on and then every build value so even our build vehicle needs to have a private default constructor so build vehicle that and underscore and then two parentheses this is a private constructor and then every build value needs to have a factory so factory build value and inside this factory we need to be able to provide a built vehicle builder and again now we are going to refer to some code which is currently not generated so just bear with me here and everything will make sense a bit later so this build vehicle factory will have inside of it like up parameter and then updates this will hold built vehicle builder called B and this will simply call built vehicle with underscore dollar sign and then build vehicle this will all be generated for us later and obviously this should not be built value but rather built vehicle my bad and also it's not a bad practice to make this built vehicle class and this whole file into its own separate library with just a name build vehicle although it's really not needed but it's just good practice to do so library built vehicle now we can save it but nothing besides the beautification of our code through the art formatter is not going to happen that is because we need to run a command in order for this built vehicle to actually generate some code for us so let's open terminal and now let's write flower packages and then we want to have a command Baba run and we want to run build runner and then we can either run build for just one time build or watch which will basically watch for file saves and whenever a file is saved it will trigger a new build so I will opt-in for watch and you should probably do always if you are working with build values you are going to change these files a lot so if you don't want to just constantly run this command just say watch and you're gonna be good to go it will take some time to initialize and you can see that nothing happens well why is that well it's pretty simple it's just that we haven't imported this built library here so let's import build value dot dart and now when we save it we can see that now it actually works but we still have some problems but this can be really simply resolved by just deleting one name one letter from the name of a property and then adding then saving again it's just a bug with Visual Studio I think so if something like that happens to you can resolve it just like that by deleting one letter and then adding it back and it will all work again so now we have a working built vehicle class when we take a look and the built vehicle dot G dot dart file which is the generated file it's really long that's because there is all of the code which you don't need to write so it really saves you a lot of time this will make the class immutable it will make it a data class so that the comparisons will be value based and not reference based but you can probably tell that creating build values like this it's a really long process just to type out all of this code is really like redundant right that's why we have snippets of code in vs code so let me delete everything what I just created here and I'm going to use my own snippets and then I will show them to you and also you will be able to get them from the link in the video description but now let's use the snippets so I can write something like B LT H which is built value header and here I just specify build vehicle and I automatically have all of the libraries and packages imported and then I will simply write BLT call it build vehicle and I am good to go so how can you add these snippets into your vs cold well it's simple just download the code from the link in the video description which is gonna take you to reso coder calm and then go over to file then preferences and you want to open up users snippets open users snippets for dart so just search search Dart and here they go and now just space everything from reso Cora calm over here and here are all the snippets I build them myself and I am happy to share them with you so we have BLT for simple build value than BLT s for serializable build value to get to that in just a bit and then we also have BL th for built value headers so that's pretty neat alright so now let's add all of the fields or properties to our built vehicle class it's going to have string get type then string brand and also double price and now when we save it we have an error in built vehicle a generated file what is that hmm that's interesting we are probably just going to delete this generated file that's always a good practice because you can just freely delete generated files you are now going to lose anything and now save this again so just change one letter added here back and save it maybe we've just messed a bunch of things up after we have deleted and recreated this abstract class so just run the watch command again yeah the simplest thing that you can always do is to just rerun your commands and now when we delete one letter and add it back we are going to be good to go so now that we have this built vehicle all explained all explored we are going to explore how we can use this built vehicle class so let's go to our code runner dart and how can you create a built vehicle well we are going to create a var car and it's going to be equal to our built vehicle so let's import the library or actually our model class over here and we can create new instances of built vehicle by calling its factory this factory will grant us a builder so B then a lambda function so to say and then inside of here we are going to use the cascading operator on this builder so we are gonna write the B and then two dots which is the cascading operator type it will be equal to car in this example because we are go create in a car obviously then the brand will be for example Tesla and finally the price so that price will be one hung 8,000 now we can print the car and launch the Android emulator so that I can show you by hitting the floating action button so now when I hit the floating action button here and then open up the console so the BA console you'll be able to see the build vehicle which is printed out which is of type car the brain is Tesla and the price is 100,000 now how do you copy a build value while copying is pretty time-consuming to do with normal classes with build value classes it's really easy all you have to do is to create a new variable so VAR copied card and it will be equal to car so our first car over here that rebuild this also grants us a builder and on this builder we want to use the cascading operator again and we will change the brand to be BMW so now we can print even the copied car and when we run the code again you can see that the first printed car is built vehicle of taya brand Tesla and then the second one is BMW so even though that we called rebuilt function on the car object it didn't change the car itself it only returned a new instance of car and also if we just create two cars which will be identical so car and car two they are exactly the same and then we will try to print out whether or not car 1 and car 2 are equal so car one for car equals car two normal dark glasses would say that these two are not equal because they are not of the same object they don't hold the same reference to the memory in the computer but in the case of value classes these two objects are the same because they hold the same data so when we run the code again here you'll be able to see that it prints out nothing because this is not an equality beresan I have to write an error equal here so sorry for that but now when we run the code you will be able to see that it prints out true yeah because these two are equal alright but now what happens if I for example don't want to specify the brand let me first get rid of the car too because we are now going to need it anymore so in the car one I'm going to delete the brand so now the brand will be not set and when we run the code now and see the console you'll be able to see that we get some error here and that is precisely that the following build value null field error was thrown while handling in gesture so we try to construct class build vehicle with null field brand this is forbidden to allow it you have to make brand you have to mark it with nullable annotation so this is really simple whenever you want to have something knowable you have to mark it with knowable so let's go to our built vehicle class and we are now going to make the brand rollable we are simply going to add another property here it's going to be boolean so bool get and it'll be called just some knowable value and in order to make it knowable so that we don't need to specify when we are creating new objects of type build vehicle we are going to mark it with the annotation knowable and now even though we do not specify some knowable value in the constructor here of the build vehicle we still can run this code and it will not crash this time because it is knowable no crashes everything works properly now now comes the question how can you add some kind of a collection to the built vehicle or to any kind of built value for that matter can you just simply add a list so list of type string for example passenger names it may seem like you can do it like this but you cannot you have to use something called built collections and there is a build collection for every kind of possible normal collection so for a list there is built list it's from the library called built collection dot dart so let's save our built vehicle file and working with built list is really simple let's jump into our code runner and we are going to add passengers so passenger names we can add passenger names by calling at all on this build list and we want to add an iterable which will be a simple list containing John Sophia they even Linda so now when we run the code it will still work hopefully so let's first open up the debug console and now when we run it so I hit the plus button yeah we have passenger names and they are John Sophia Dave and Linda so everything works and still the brand in the first car is Tesla in the second one it's BMW alright but I really do not like that the type of a vehicle is a simple string because yeah it's car it can be a train it can be a plane but it can also be some gibberish right this is just not good we need to change it to be an enum but we have a problem with enums because enums in dart are really not classes and they are not all that powerful but thankfully build value comes with its own enum class so let's go to our built vehicle file and we are going to create our own enum so let's create a new class under our built vehicle it will be called vehicle type it will extend enum class all of the possible vehicle types are going to be specified as static constant fields so static cons vehicle type called car and it will be equal to something made up so you can add any name here because it's going to be generated for you by the code generator but the good practice is to just add underscore and dollar sign and then Carr we're going to do the same for a motorbike train and plane and you can get the code from the link in the video description if you don't want to type everything out then every in our class needs to have a special kind of constructor it will be a constant constructor so vehicle type and then it will be private so that underscore it will obtain one string name and then it passes this name string to its super constructor so dispatch name to the super constructor and you are good to go then every enum class has a getter for values which will simply return the list of car motorbike train and plane so this getter is called values and it's static built set set is basically a collection which can contain only one element of a certain value so build set of type vehicle type get values it's going to return underscore dollar sign and then values then also it needs to have a function value of which will get a name so static vehicle type value of which gets the string name and it will return a vehicle type for the name so for example if we pass in car string it will return this vehicle type car it will call value off which is a generated function so again underscore dollar sign value off and pass in the name again we were getting built errors but simply deleting one letter and then adding it back in solve all of those problems so really that's just back of vs code I think and now what we can do is that we can change the type of our type property in our build vehicle from string to our enum a vehicle type so we can no longer specify some gibberish into our type because it will not build so save it again and when we now go into our code runner you can see that you cannot specify something of type string as the type so we need to specify vehicle type and this case is going to be car so da car and let's mix things up a bit in the copied car it's no longer going to be a copied car but rather a copied train so we want to also print out copied train and in addition to the brand it also will have changed type so cascading operator and then type will be vehicle type and then train and also because it is train it cannot be BMW I think that BMW doesn't make trains as far as I'm concerned so it will be some different brand and I think that Skoda transportation is a good candidate for that so I will even change to my Slovak keyboard here and right Khoda transportations or transportation I looked it up on Wikipedia there is a real brand of trains of train cars of locomotives so now when we run the code it will run just fine and the output is that build vehicle is first type car Tesla one hundred thousand and the passengers stay the same and then the second built vehicle is strange code of transportation and the other two properties stay the same alright so we've covered the basics of build value we've added nullable fields we've also added in amps we explore how you can add collections to your build value classes and that is by using built collections but we are still missing one thing which is really awesome about build value library and that is really simple serialization so let's add it right now in order to make a class serializable you basically need to add only one line of code into your class and that is static serializer of type built vehicle it will be a getter called serializer and it will return something generated called underscore dollar sign and then built vehicle serializer this will be for us in just a bit this is all you really need to add here in order to make this class serializable but what I like to do is to also add some helper functions for converting to JSON and also from JSON so they look something like this - Jason calls JSON during code and we encode the output of calling serializers which will be generated for us and then serialize with build vehicle serializer and we want to serialize this instance of built vehicle so this is here and then from JSON we'll obtain a JSON string and it will return an instance of built vehicle and also we are deserializing with build vehicle serializer and we decode JSON which is passed into this function as a JSON string and also you can get all of these helper functions and also this serializer when you create a new class as blt as from the snippets which I provided at the beginning of this tutorial because BLTs does something like this it adds to JSON from JSON and horse also the serializer here but we are now going to use it because we've already added those lines of code ourselves now this still wouldn't work because even though built value serializer can serialize every single basic type which is present in dart and also built lists are serializable and also built maps and build sets and all of that the problem is that we have our own custom type in here which is vehicle type and vehicle type is not yet serializable so we need to make it serializable by adding one line of code over there and that line of code is basically identical to the one which is present in and built vehicle but it's going to be for vehicle type so serializer vehicle type get serializer and then it returns vehicle type serializer now in order to make this all work we need to add one new file under the model it will be called serializers dart inside here we are going to use the Snippets OBL th4 header it will be called serializers and in here we want to create a top-level field it will be final serializers serializers and it will be equal to underscore dollar sign and serializers now we need to annotate this stub level filled with serializers for this contains a constant list and this will serialize built vehicle and vehicle type added here import it and now save it you can immediately see that we have generated serializers ger dart over here and also save built vehicle dot Dart now we still have some errors over here but we can fix them by clicking on serializers which has an error on them and we need to import these serializers so control that well it seems that vs co doesn't offer any code actions but we can import them manually so that serializers field which we are accessing or trying to access here is present under so import serializers dot dart it's under the same folder so that's why we can just specify it as that otherwise you would need to specify its path alright so now we are not getting any errors so we can go to our code Runner and convert our car to JSON so final car JSON is equal to car dot to JSON and we will print this JSON so print card JSON and also we are going to create car from JSON so it's gonna be equal to a new built vehicle and we are going to create that built vehicle from JSON pass in the car JSON string so this one here which we have just created and we are now going to leave it as that we are going to modify this built vehicle a bit so rebuilt B for builder and on this builder we are going to MA find the price to be only 2000 dollars or Euros or whatever and then we are going to print even this car from JSON alright so let's open up our debug console here we have some errors which were previously present but hopefully they are not present now and when we now press the plus floating action button the code will run and you can see that these two first cars are printed out so that's cool but then we have printed out the JSON and also the new car which was made from JSON and it's price is 2000 s set here but if you take a closer look at this JSON you can see that it's a bit weird isn't it typically JSON has key value pairs but this has just a list of string values the type of our vehicle is surely car and the brand of our vehicle is Tesla but usually you would have type Colin car and then brand Colin Tesla but here you have just commas in between so what's up with that well it turns out that build value library has its own kind of JSON serialization but there is not a huge problem because you can create a valid typical JSON with just adding one line of code into our serializers dot dart so let's do that right now so we need to wrap this serializers in parentheses and then we want to convert this serializers to builder we want to add a plug-in on that and the plugins name is standard JSON plugin we also need to import it alright no import is available so we need to import it manually so just write import stem dirt jason plug in dart and we wanna call the built on this now when we go back to our code runner and OH and up the console here so debug console open up our emulator and run the code it's still not changed why is that well it just turns out that we need to make hot restart so not f5 but ctrl f5 when you are using fluttered as I said this is not a flower tutorial so if you are using just pure dart counsel AB you can just you're probably not going to have this problem so if you are using flutter and following along this tutorial just hit ctrl f5 and you are going to perform hard restart and now with the hard restore in place when rerun we run the code again you can see that the hard restart had its the effects because now this is a JSON that you would expect so still even the to JSON and also from JSON works even though we have changed the format of the JSON a bit in just a quick pro tip at the end if you don't want to see this generated file so those dodgy dart files you can go to settings so ctrl + comma and search for files exclude and you can add a new pattern and that pattern can be two asterisks then slash asterisk and that G dot dart and ok and you'll be immediately able to see that these two files were hidden from me but they are still in the file system so you can access them by viewing this from the Explorer so reveal and Explorer and yeah they are still here but they are hidden in vs code alright so I hope that this tutorial helped you I really wish I had something like that when I was starting out with build value because it's really more on the hardware side to learn a library like that because it has so many possibilities so definitely if you liked it and if it helped you this tutorial give it a like and also share it then also definitely subscribe to this channel if you don't want to miss some more tutorials like this where from dart or from flower and also hit the bell button so that you are not going to miss any of my new videos and you are actually going to get those notifications leave a comment if you have anything to say follow me on Instagram Facebook and Twitter and see you in the next video [Music]
Info
Channel: Reso Coder
Views: 23,617
Rating: undefined out of 5
Keywords: resocoder, tutorial, programming, code, programming tutorial, dart, flutter, built_value, built value, dart data class, dart serialization, flutter serialization, dart immutable class
Id: Jji05a2GV_s
Channel Id: undefined
Length: 33min 52sec (2032 seconds)
Published: Wed Jan 16 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.