Understanding Null Safety in Flutter using real world example - Part 1 (coderzheaven.com)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi welcome back in this video we will learn about null safety in flutter with the help of a real world example so let's start as usual i'll be starting with an empty template with just a main.rt file and it's having an empty container uh with a white background set as home so you can see that on the right side so let's go to the pubspec yaml file there you can see uh we have not added any dependencies yet so let's go to the pub.dell copy the http package and paste it under the dependencies in pubspec and call flutter packages kit and install the packages now let's create a screen i'm gonna create a file home screen dot dart and create a class inside it which i'm going to call home screen and import the material package so you can see that there is an error in the key parameter that's because our project is not yet set up for null safety so let's go to the pubspec.yaml file and make our project compatible for nut safety let me go to the pubspec yaml file and change the environment from 2.6 to 2.12 which makes our project compatible with null safety now i'm gonna create the contents for the home screen so a scaffold with an upward and a container and let's create another file called user services now let me show the service that we're gonna parse so this is the one i'll be providing the link to it in the description it has 10 records now and each record is having sub objects like address and address is having the latitude and launch tool which is jio inside and the company object as well so let's parse this let me copy the whole response and go to app.qtype.io so i have made another video on how to create models easily with app.cubetype.io i'll be providing the link to it in the description so here just paste it give it a model name and i'm going to make all properties final okay so make all properties final and copy the model classes that is generated so you can see all the sub objects and every classes has been generated let's let's dig into it more deeply so let's create another file i'm going to name it user underscore list underscore model dot dot so paste it there so you can you can see there are so many errors so we're gonna fix it that's because of the null safety let me rename the domain class to user so each record is a user recorder okay so you can see the address object address has all the fields in it and address has the geo object inside it which has the latitude and longitude so if you go to the response you can see that that's the g object and you can see the company object as well it has the name and other fields now let's go ahead and fix these errors so if you look at the id field it says that the parameter id can't have a value of null because of its type so it's an integer type and it doesn't have a value now so that means it is null and we cannot have a value of null right so the first way to fix it is just by adding a required keyword in front of the id so that means whoever using this object needs to supply the id with a proper value other than null because the id which is an integer is not nullable now then how do we make a parameter nullable so just by adding a question mark at the end of the type you can make it nullable so here i have made name username and all other fields nullable by just adding a question mark at the end of the type so let's go ahead and do the same thing for the address where we have street city zip code and we will also make the geo object which is another object and made it nullable that means it can accept a null value so let's go ahead and so you can see one error here we'll fix it in a short while let's make the latitude and longitude level and similarly for the company class let's make all the member variables also nullable but we have some more errors here right in the two json method call on some of the variables it's saying there is some error that's because we made the so for example here we made the address object nullable and it says that you cannot invoke a method on a nullable object because it might be null and it can crash the application so how do we fix this so just add a question mark at the end of the variable and it tells the compiler that don't execute the 2js1 method if the variable is null so this is just a safer way to prevent the null exceptions so it will just return from there without executing the two json method and so that will be just returning the null and it won't crash your application but there is another way to fix this error you can just put an exclamation mark instead of a question mark but you should be very careful when you use the exclamation mark because you should be very like you should be sure that this variable will never be null because it's going to execute the 2json method even if it is null it will the compiler will just unwrap the variable even if it is null and it will just execute the 2json method and it can crash your application so it's recommended that it shouldn't be used in a production code so make sure the variable that you are just going to use with an exclamation mark can never be now if you want to use it so that's about the two operators so if you remember we made the id required so that means it can now be null and so the compiler is showing a warning here it will never be null so this condition this conjugation the id is equal to null is it's this that doesn't make any sense so we can just remove it so we had cleared all the errors from this model and let's see how we can use this so let's go to the user services dot dart file but before that let me create one more file api status dot dot and declare two classes success and failure and we're gonna use these classes inside the services class the success class will have a code and a response which is of type object as you can see we need to initialize it or we need to make it required or give it some value right so i'm going to make it required in the constructor of the success class response also required now the error is gone let's make the similar changes in the failure class so here and just renaming the response to error response and change the constructor to failure and error response as well okay cool so now these classes are ready to be used anywhere in your app so let's change the user services class create a new class class user services here we will have a method to get the data from the service but before that let me declare some constants let's create a new file constants. and let me paste in some constants here so these are the constants that we are going to use when we call the services we have the url and some other constants for invalid response no internet and honor and success now let's write a method to get the data from the service i'm going to call it get users and inside the try catch method i'm going to say our response is equal to await let's import the http package await get that will be users list okay we have some error here so we need to pass in the uri so uri.parse with uses list let's catch some exceptions here the first one would be http exception second one is socket exception third one format exception and fourth one let's leave it as just a catch for all all the other errors so i have made another video on how to catch exceptions properly and show errors and everything so i'll be providing the link to it in the description now let's get the response and and if the status code is 200 which is success we are gonna call users list from json and return this success object with success code otherwise we are going to return the failure and the constant invalid response and for error response we can just pass in the string for now and similarly for all the other exceptions and let's change each message to no internet for http exception and for socket exception and for other exceptions let's say invalid format and the last one is unknown error okay let's change the constants as well so that would be invalid format no internet invalid user invalid response so now that our services class is ready let's use it in our home screen we are going to need a couple of variables here first let me overwrite the end state method so init state remove the command and the variables that we are going to need now is list of users because we are going to gonna display the list of users from the service right so list of user user list let's import the user and as you can see there is some error because we have initialized our user list right we need to give it some value initially or we can make it nullable so we can just add a question mark at the end of the type to make it nullable right now it's null but or another way is make it late you need to increase it later but make sure that you initialize it before you access it otherwise it's going to be resulting in error so here this is how you can initialize it later later or in the init state or in any other way before you access it for now i am just gonna initialize it to an empty list in the declaration itself we will also need another method to call the method in the service to get the data in the ui so get users who are reserved is equal to oh wait this is services dot get users so that will get us the list of users from service and we're gonna check if the result is success we need to get the response from the success object and cast it to list of user and call setstate so that will refresh the ui otherwise if the result is a failure let's leave it empty for now we will handle it later and call getservices in the init state now let's display the list of users in the ui for that let's add the list view dot separated widget and in the item builder let's return an empty container for now and a divider for separator builder item count would be uses list dot length now let's write a separate widget for the list row it's gonna accept a user and a function on tab as parameters so the constructor is showing error because we haven't added the user and on tab to the constructor so let's add it this dot user still it's going to show error because we haven't initialized it yet so either we can make it nullable or we can make it required so i'm going to make it required because we need the user object for the list row now for the ontap function i'm going to make it nullable because we may not need it all the time and i want to show something like if we are passing the line how we can prevent if the function is passed as null and everything so please be patient and we'll see it in a short while so let's create the ui so in the ui for the list row we will have a text and another text for email the first one for name and second one for email so here it's saying the text will not accept a null because here the name can be null right we had made it nullable and the textview is saying if it is null the textview is not going to accept it so let's unwrap it so for now we have just unwrapped it but beware that um this value can be null and it can result in errors if the user.name is actually null so let's use the user list row widget and pass in the name so that would be user list of index as user and we are not passing in the ontap function here now let's set the home screen as home inside our my app widget which is our root so we are getting some errors that's because of the list view inside the column and the reason is both are unbounded height and we need to give it a height or you can add shrink wrap so shrink wrap is not recommended it can cause performance issues or you can wrap it inside and expanded with it so for now i'm just setting as shrink wrap to true so we have the data in the ui so let's go ahead and make the user dot name is equal to null and see what happens so it's saying there cannot be a setup because it's final so for now i'm just removing the final from name so we made it null so you can see the text view cannot accept a null value so the ui is throwing the error so null check operator on a null value so we are trying to unwrap a null value here which is null so it's going to result in the error so using the unwrapping like this is not a recommended way to do it so what are the other options we have so let me remove this from here and undo it let's do the checking from the from the class where we parse the data so that's the user list model i'm gonna refactor the from json method to return the user object like this and i'm gonna make the json name to null from here itself so where we are parsing the data so here let's set the value to null directly and refresh the ui is going to result in the error so so what if the value from service is actually null so we are already checking the null here so if it is null we are setting it to null actually right so we don't want that so if it is null let's set it to an empty value and let's assume that the value from service is actually null so i'm trying to set it to null so when the service returns we'll set the name to null and you can see that ui is not crashing it's going it's setting it to an empty value let's try to set it the text empty so you can see if the value is null it's going to return empty let's remove that and and this is another shortcut for the null check that's going to do the same thing that we did earlier so let's try to change it to empty so it's the same thing so that's a cool handy way to do it to do the nut check okay yeah so that's that's one way to prevent all these null exceptions so one more time without the null check let's remove the analytic from here and if i refresh the ui it's going to result in the error right and then i'll check operator on a null value so if i if you go to the the deeper console you can see the same error and i'll check operator on a null value so let's go to user list row there we are trying to unwrap a null value so let me show you one more thing so what if what if the service is not even returning a json name key so what what would be the value then so we already made it nullable so it will be returning null but we want to give it a default value if the value if the key itself is not even returned from the service so you can see this is how you can do it in the in the declaration in the constructor itself so if you change it to empty you can see it's taking the default empty value because we are not even parsing the name key in the from json let me uncommend it now we have made it null and if i refresh the ui so as we know it it should crash because we are trying to set a null value right let's remove it and refresh the ui so it's displaying the ui properly now let me just give it some spacing and arrange it arrange it properly okay so let's look at the name once more now this time let's remove the nullable operator and you can see there is a warning so tata says that we don't need this operator anymore because it's not non-local right now so it should have a proper value so that's what it's assuming so we're gonna check we need to put back the null check here so what if the service is returning now you need to give it some value right so let's leave it empty or let's remove it and see what happens let's try to set the value to null and see what happens so flutter assumes that there there will be some value but we are trying to set it to null so we are thinking that the service actually return null so still the ui is going to crash because our text view cannot accept a null value so it's going to crash in the user list row itself because the user dot name is null so we need to have the null check here let's set it empty if it is null refresh the ui and see what happens so the ui is not crashing now let's try to set it to the to the value empty and see if it is being displayed in the ui and also wrap the text widget inside a disability widget and make it visible only if it is if the user.name is not empty okay now let's refresh the ui and see let me remove this and if we refresh the ui it's the users and it's going to display the proper name and let's make it null and so now it's not taking up the space because we had added the visibility widget and it will make it invisible when it is empty and not take up this space so here we have a warning we don't need a null check here in the 2json so we can just remove it so the code is much cleaner now you can apply it for other properties as well so that's all for this video in the next video we will see how we can apply the null safety features to more complex objects like uh for example here the company object so that's that's another nested object inside our user object right so we can we'll see how how we can apply this in our safety and how we can prevent those null exceptions and errors in our projects and make it much more stable so if you like this video and if you found the video useful please don't forget to like subscribe and share i'll be uploading the next video as soon as possible the link to the source code for this demo is provided in the description so please check it out so thanks for watching and see you in the next video until then bye
Info
Channel: Mobile Programmer
Views: 2,499
Rating: undefined out of 5
Keywords: Flutter, Google, Android, iOS, Tutorials, Code, Study code, Cross Platform, Dart, null safety, null check flutter, null safety errors
Id: VGRlVKHBvwg
Channel Id: undefined
Length: 25min 8sec (1508 seconds)
Published: Sat Jan 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.