How to use @EnvironmentObject in SwiftUI | Bootcamp #51

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's up everyone welcome back i'm nick and this is the perfect video to follow the last video so if you did not watch my last video on state objects and observed objects definitely watch that one first and then come on back to this one because in this video we're going to look at the environment object and it essentially is the same thing as a state or an observed object except this one we can actually put into the environment and all that means is we can add it to the background on our app or on our view hierarchy and then all of the views in that hierarchy will have access to this object so this is perfect if we have some sort of class or object that we want to use in a whole bunch of different screens and we don't actually want to pass in that object from screen to screen to screen to screen instead we just put it in the background put it in the environment and then each screen can individually reference this object so it's perfect this is the power of swift ui and i hope you guys enjoy it all right welcome back everyone i'm of course in xcode again let's right click the navigator let's create a new file it will be a swift ui view of course and we're gonna call this one environment object bootcamp go ahead and click create once you're inside click resume on the canvas should be used to this by now and let's get ready to get coding now there is some setup we have to do for this video and if you do not watch my last video where we learned about state objects and observed objects i would recommend watching that one first and then coming back to this one because this is kind of the more advanced version of that so first you should learn observed object if you do not then you should learn state object which is kind of the same thing as observed object and now we're going to look at environment object and environment object is basically the same thing as a state object except we can put it into the environment and by putting it into the environment we don't have to actually pass this object around our app instead all of the views in our app in this hierarchy will automatically have access to this object because it is in that background environment so let's get started here let's create a very simple app let's create a navigation view open the brackets inside we're going to add a list open the brackets again and then we want some data for this list so let's create a view model class to host our data so let's create a class i'm going to call it environment view model and let's make it conform to observable object open the brackets and we're conforming to observable objects so that we can when we implement it in our view we can tell the view to actually observe this object i covered this in the last video where we covered observed and state objects so you this should not be new to you and in this environment view model let's create uh some data so let's do at published var data array of type and let's just do an array of string for now let's set it equal to a blank array and then let's create an init function so when this viewmodel actually gets created it's going to call this init function and when we init we want to fill up our data array with some values so let's create a function to fetch and store values into this data array so we'll do funk get data open close parenthesis open the brackets and of course we don't have a database or anything so we're just going to append some fake data to this data array let's just do self.data self.dataarray.append and we need a new element here of a string so the data we're appending here doesn't really matter because that's not what we're talking about so let's just append some maybe ios devices we'll do uh iphone and then let's self.dataarray.append we'll do ipad and there's actually an easier way to do an append with a bunch of contents so let's do self.dataarray.append and this time let's use the content of and this wants a sequence which we can do by using an array so let's just create an array and then here i'll just append iphone comma we'll do ipad comma let's do uh imac and maybe uh apple watch let's get rid of these first two appends here and all that really matters here is that we are going to append these four items to our data array so when we init let's call get data and that should be it for this actual class now i want to note here that in your real app this is not going to be called environment view model this word environment will probably be based on the screen so if you had like a home screen this would be like home screen view model it's a better way of naming it and then in this you would have all of your functions to fetch data store data save data go to your database and that all that logic would be in this class but we're not covering that right now so all you need to know is that all of our data is within this class object so let's reference this object in our view now so down here where we have the environment object boot camp view this is the view that's on our preview on the right side here so let's create an at state object var let's call it view model and it will be of type environment view model and we'll set it equal to a new environment view model open and close parentheses now in this line we are creating a new environment view model we are initializing it right here with this open and closed parenthesis so as soon as we initialize it this init is going to get called it's going to call get data it's going to append the data to our data array and now we can access that data through this view model and so in this list here let's do four each open the parentheses let's use this third completion here with the id we're using the id here because we don't have ids for all of these items because these are just strings in the last video we used a custom data type that conformed to identifiable so because though they had ids already we use the other for each completion but since these don't have ids we're going to create ids in this loop here so let's just do the data is going to be view model dot data array again that's referencing this view model and then the data inside the id will be backslash dot self this is just creating an id basically for each of these items in the data and then for the content let's hit enter let's get rid of this ugliness and we are looping on each uh let's just call it item for now so in this list let's just add a text with the item click resume on the canvas just to make sure we are all set up here all right iphone we have our data on the screen let's underneath this list add a navigation title let's call this ios devices now when i click on one of these devices i want to go to the next screen maybe a sub screen for that device so instead of just having a regular text here let's make each of these a navigation link i did a whole video on a navigation view a navigation link so this also should not be new to you we'll add navigation link here open the parentheses and we're going to go down to the destination and label completion so the destination is the next screen and right now we'll just leave that as text destination and then the label is what we want to look like on this screen so i'm going to cut this text with the item and just paste that in the label for now so immediately on our on our preview we can see that it did update we had this nice little indicator icons on the right side if we press play on the live preview when we click this word iphone it's going to bring us to the next screen right now that next screen is just a destination so let's create a custom second screen here and under i'm going to do that underneath this view we're going to create another view let's so let's create a struct let's call this uh maybe detail view this will be of type view and let's open the brackets now we know every view needs a body so let's open the brackets again and in this body what do we want that second screen to look like let's give it a z stack open the brackets let's give it a background layer so i'll make a comment here background and let's give the background maybe color dot orange dot ignores safe area just give it a background color and top of that let's add some text i want that text to be the item that we clicked on so when we create this detail view let's add an init let's add a variable that will be in our knit so it determines what we clicked on so let's say let selected item and it'll be of type string so when we create a detail view it will ask us for a selected item and let's just put that on the foreground layer and we're going to do just maybe text with selected item let's give it a font of headline let's give it a maybe foreground color of orange let's give it a some padding let's give it some extra horizontal padding so we'll do padding dot horizontal let's give it a background color of color.white and a corner radius of 30. just to see what this looks like quick let's put it into our preview down here so i'm going to comment out the environment object boot camp and just put in our detail view see what it looks like click resume on the canvas oh i forgot that when we create our detail view we need to tell it a selected item so let's just add iphone click resume on the canvas let's see what it looks like i think it'll look good that looks good that's all we wanted on this screen obviously in your real app you're going to have more information than this but this looks good so let's incorporate this into our app so far let's put the environment object boot camp back comment out the detail view i'm going to scroll up to where we have our destination right now right now it's just a screen that says destination but we're going to change it to a detail view open the parentheses and in our knit we need to have a selected item of course that is going to be our item let's click resume on the canvas click on ipad we have our selected item it says ipad very nicely and now one more step for this video i know this is a lot of setup but this is good practice when we click on this ipad i want to go to a third screen so let's create another view here so that when we click on this ipad we can go to a third screen in this hierarchy so underneath the detail view i'm going to add another view and this is why i'm doing this video towards the end of this course because it is a little more complicated but you're going to see why this is so cool so let's create a struct this will be a final view let's just call it this will be of type view open the brackets and what does every view need it needs a body open the brackets again so in this final view let's add another z stack open the brackets let's add a background layer let's give it a gradient just because we haven't used that very often so let's do a linear gradient open the parentheses and press enter on the gradient colors i'm going to put these on different lines here so we have gradient we have our start point we have our end point and i'm going to go from the top left to the bottom right so top leading to bottom trailing and let's switch up these colors so i'm going to delete this color red and just add color open parenthesis and start typing color literal here for the color literal i'm going to use maybe this blue here i don't know what exact color it is and then for this one i'm going to delete the color blue and type in color open parenthesis color literal and i'm going to find a darker version of this blue so last time i used i think this one let's just use this darker slightly darker so we have a nice shade from the top left to the bottom right let's take this final view and put it in our preview really quickly so let's comment out the environment object bootcamp and just add a final view open and close the parentheses and let's see what it looks like quick uh looks good but i wanted to go to the full screen so i forgot to add dot ignores safe area full screen and then on top of this let's add a foreground layer and on the foreground we're just going to add a maybe a scroll view open the brackets in the scroll view we'll add a v stack with spacing of 20. open the brackets again and in here let's just add text with item 1 text with item 2 item 2 and text with item 3. uh let's on this v stack let's add foreground color of white and font of a large title maybe these items are bigger and when we're actually in this we're going to be in a navigation view so there should be a navigation bar at the top but we're not going to worry about all that right now this looks good to me this is going to get our point across so let's connect this to the rest of our app let's first put the environment object bootcamp back in our preview comment out the final view let's go up to our detail view and in our detail view when we click on that selected item i want to navigate to the final view so we're going to do that again with a navigation link so navigation link open the parentheses we're going to use the destination and label and the destination of course is going to be final view open and close parentheses the label is going to be that button that we created earlier let's cut it let's paste it into the label and let's check this out quick let's click resume on the canvas we have our screen one here i'm gonna click on imac and we're on our second screen that's this detail view and we can see that we did click on imac because that's what's coming up in this button when i click on this button we should now go to our third view which is our final view so let's click on that final view and here we have item one item two item three and of course we can go back through that navigation hierarchy if we want but the point of this video is to look at the environment object which we have not used yet and the reason i've set this up this way is because what if on this third view we want to access this data array so this iphone ipad imac all that view model what if we wanted to access that not only on this first view but also on this second view and also on this third view well there's two ways that we can do it and first i'm going to show you guys these the state object and observed object way this is what we learned in the last video so right now at the top of our view here i know we have a bunch of views i hope this is not too confusing but in our first view we have a state object with the view model now if we want to pass this view model to our second view to our detail view we could add in the detail view at observed object var view model we'll call it and it will be of type environment view model so when we create a detail view it will ask us to pass in this view model so we're going to get that error back in our first view here so it's saying where is this view model let's fix it and let's pass in an environment view model so this view model we're just going to pass it in when we go to our destination now our detail view has access to that view model so detailed view has access but now what if we want to get it to our third view to that final view well in the final view again we could add at observed object var and let's call it view model again and it will be of type environment view model so now again when we create a final view it's going to ask us for a view model so we're going to get that error on our second screen when we create this final view it's saying hey where's the view model so let's pass in again a view model to our third screen so now this final view has access to that same view model and in our final view here we now have a view model so in our v stack we can access the view model directly so i'm going to delete these text items here i'm going to add a for each open the brackets let's use the id and content the data is going to be the viewmodel dot data array and that's the data array we made at the beginning of this video id again let's just do backslash dot self and then for the content we'll hit enter get rid of this ugliness i'll call it item and we're just going to add text with the item so let's click resume on the canvas wrap up what we did so far so on the first screen i'm going to scroll up here and walk you through it on the first screen i'm sorry if this is getting repetitive on the first screen we initialize the view model with a state object and we did the state object so that it does persist if the view has to re-render for whatever reason so we have our view model then we go to the second screen when we click on ipad and when we go to that detail view we are passing the view model into the second detail view so on the detail view we created an observed object and we're observing that view model so we passed it in and now we have access to this view model on the second screen so although we're not using it on this second screen we have access to it so we could use it if we wanted to but there's nothing on this screen that actually needs it and then when we click on this ipad button we're going to a third screen to that final view and again we're going to pass this view model into that final view so i'm going to click this and now in our final view we created another observed object that will observe that same view model that we passed through the hierarchy and on this final view we can now use that data in this view so we have the iphone ipad imac we have access to that data on this third view so we didn't have to create a new view model we didn't have to create a new environment view model but instead we just passed the one that we created through the hierarchy to this third view now this is great and this is efficient but there are cases in your app when you're going to have sub views on sub views and it's going to be more than even just three views you might have five or ten views into your hierarchy and when you have something like that it might get really annoying and confusing and repetitive to have to create an observed object on every single screen and then pass in your view model from screen to screen to screen because for example this second detail view didn't even use the observed object we passed it in so that we could get it to our third view but we actually don't even need it in this in this whole view right like it's just here just to get it to the final view it's not here because we actually need it on this screen so this was kind of like extra code so what we're going to do is take this state object that we initialized here and then we're going to put it into the environment so this way once it's in the environment all of the views in that hierarchy will have access to it so we no longer would need to pass it directly into our app but all the views would just have access to that environment so we have our view model here and then on this navigation view i'm just going to add dot environment object and then the object is going to be our view model so we're taking this view model that we're creating right here and we're putting it in the environment and now all of these sub views that derive from within here so pretty much anything in our navigation view whether it's one screen in 10 screens in a hundred screens in they're all going to have access to this view model so because they already have access to this we no longer need to pass it into our detail view it will already have access to it so i'm going to go down to our detail view and we don't need to pass this in anymore so i'm just going to delete it because we actually don't need it on the detail view at all and then i'm going to move down to the final view where we have this again and of course we're not going to pass an observed object into this final view instead we're just going to pull that object from the environment so i'm going to use at environment object here and the only thing to be aware here is that by adding this line you need to know as the developer that there is an environment view model in the environment because if you add this and there is no environment view model in the actual environment then you're going to get a crash but we know because we just added this that we actually have this view model in the environment so when we create a final view we no longer need to pass in a viewmodel directly it's just going to pull this from the environment so if i scroll up here we no longer need this initializer for the final view so i'll just delete that and you'll notice here that the detail view doesn't even have a reference to the view model because we don't need it in that detail view so there is no more observed object here we're not passing it in here and back up on our first view we again don't need to pass in that view model to our detail view because we're just throwing it into the environment so i'm going to delete viewmodel from our init here and you can see that even our inits are just getting cleaner now because we have this in the environment we don't need to pass it from screen to screen and let's click resume on the canvas and watch this magic on our first screen we are creating the state object which is our environment view model here we're throwing it into the environment and then we're going to go to our second screen which says iphone so when we click on this detail view we go to that second screen but we're not actually passing in the view model we're just going to that second screen and in the background of this detail view is that view model but because this detail view did not actually need to use that view model we didn't need that line of code we didn't pass it in and then we just go straight to our final view so let's click on iphone and when we get to our final third view here we just pull that view model from the environment by using an environment object and we have access to that list to that data without having to pass it from screen to screen to screen so this is the power of the environment object once it's in the environment all of the views in this in the hierarchy will automatically have access to it and it just makes our life as developers so easy because we no longer need to pass this from screen to screen to screen we can just throw it into the background and then now you have this nice environment object and this is really cool really important because if we update this view model from this third screen if we if we add data delete data if we change data it will also be updated on all of the other views that are using this same environment view model so this is a very very efficient way to pass data around our app without actually having to pass it from screen to screen screen so that's pretty much it for this video i hope you guys enjoyed it i know this was a longer one but before we go i just do want to mention that the environment object should be used kind of sparingly like this should be there should only be a couple objects going around the environment in your app if you have a bunch of different view models you probably don't want to add them all to your environment because it might slow down your app but even more than that it might get confusing to you as the developer and your teammates to have so many different models in your environment so i would really just keep the environment object for items that really need to be used on a bunch of different screens maybe throughout the hierarchy so if you have a bunch of different screens and only a couple of them need access to this same view model use the environment object but if you have a case where only one or two screens need that view model so if if we were just creating this list and we only had one detail view then i would keep it simple by using a state object in the observed object that we did in the last video the environment object really comes into play and it really becomes handy when you have a larger view hierarchy so thank you guys again for watching leave a comment if you enjoyed this video or if you're still confused and i'll be happy to answer your questions as always thank you for watching i'm nick this is swiffle thinking and i'll see you in the next video
Info
Channel: Swiftful Thinking
Views: 5,395
Rating: undefined out of 5
Keywords: SwiftUI Bootcamp, Learn SwiftUI, SwiftUI Environment Object, SwiftUI @EnvironmentObject, @EnvironmentObject, What is @EnvironmentObject, EnvironmentObject, EnvironmentObject vs ObservedObject, SwiftUI what is Environment Object, SwiftUI how to use environment object, @EnvironmentObject SwiftUI, What is @EnvironmentObject SwiftUI, SwiftUI Environment object vs observed object, @EnvironmentObject not working, @EnvironmentObject crashing, @EnvironmentObject causing crash
Id: VWZ-h_N1wDk
Channel Id: undefined
Length: 26min 47sec (1607 seconds)
Published: Thu Mar 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.