Flutter Hive - A Simple Example to Persist Data in a Local NoSQL Database with Hive & Flutter [2022]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hive is a key value database written in dart you can use it in your flatter apps to persist data locally if you close the app data will disappear unless you have saved them into a database in this video we are going to create a simple app with a list of movies stored in a hive box that we will call the movie's boxer users will be able to write and read to and from the box and all the movies will be persisted on the local memory using hive then we're going to create a more complex version using hive and the block pattern here we will have all the business logic in the movie block and this will be connected to the box using a custom class that we will use to perform crude operation now let's go back into our code editor and get started so let's take a look at our boilerplate code first of all we have a material up and here we are customizing our theme by using the team data widget and we are passing some color then we have set the home equal to our home screen widget which is a stateful widget that represent the screen that you're seeing right now here first of all we created a variable called movies and this is going to be a list of a movie object in every movie that you see on the screen as now it's stored inside this variable then in the scaffold we have an app bar in which we're showing the title and an icon button the body is equal to a list view builder in which we are passing all the different movies from the list and we are returning a different list style for each of the movie that are in the list in the list style we are simply showing the image of the movie name of the movie and a few icon buttons one to add it to the watchlist one to remove it and one to edit the movie and finally in the bottom part we have a floating action button and if the user click on the floating action button it will show up a model bottom sheet because we are invoking the show model bottom sheet method and here we are simply creating a few variable to control a few text widgets and then we are using the show model bottom sheet directly to open this menu from the bottom in the menu here basically we have a couple text field so that the user can input the name of the movie and the image url of the movie and then we are just saving them and creating a new movie object by using a delivered button and by adding the movie to the list moving using the set state method and finally once you click after we add the movie to the list it will just invoke navigator.popup and so we will close the modal bottom sheet now that's pretty much it let's try to add a movie so let's copy the image url of this movie and let's paste it here so first we have the name and then we paste the image url as you click save you can see that movie will show up on the screen and for now you cannot click on any icon yet however if we close the app and we try to restart it you will see that both the movies have been deleted from the list in fact we did not persist the data into the memory of the app in fact every time you close it unless you save them to a database or to some local storage you will not see the data anymore and in this video we will use hive in order to persist the data across different sections now before we get started let's also take a look at the movie model here we have four different variables the id the name the image url and the other two watch list boolean all of these are required to create a movie object and then we have the copy with method that we will use in order to create new movie object by changing one of the parameters and then we have the props and later we will edit this model in order to make it work with hive now let's go to a hive documentation and start to add all the dependencies that we need in order to add hive into our project so we need to add two dependencies and two depth dependencies so let's go to our pubspec.yaml file now inside the dependency you need to make sure that you have hive and i've underscore flatter just check which are the latest version and add them to your project and then you need to have hive generator and the build runner dev dependency as well and now in this project you also need to add flatter block and equitable if you want to follow along now let's continue and the first thing we need to do is we need to understand what is a type adapter so into the hive database you can save all the different primitive types including list map string and so on and so forth however if you create a custom model and you want to save the type of object inside your hive database you will need to create a type adapter the type adapter will let you convert your object into a binary form that can be saved inside the hive database so that's why you need to create it so first of all let's start to create our type adapter for our movie class first we need to annotate the movie class with the hive type we will add the type id equal to zero but remember that if you create multiple type adapter each one will require a different type id then for each of the field in our class we have to add high field and we need to specify a unique index for each of the field now if in the future you will edit any of your fields or if you change the data type you will also need to change the id or the hive fields as well and finally let's add part of moviemodel.g this will help us to generate another file and to do this we will use the build runner dependency so now let's go to our terminal and let's write flatter packages pub run build runner build as we do that we will have a new file created in the same folder of our movie model and this will be the type adapter generator so now we need to wait a few seconds and as you can see the file is there in the folder so if you open the file can you see this is the type adapter generator and this is converting our model into a binary that can be saved into hive and every time you create a new type adapter you will also need to register it so for now we are good to go so let's continue now let's go back to our main data and let's start to create our hive boxer so first of all we need to use widget flatter binding.initialized then we can start to use hive and we're going to use init flatter in order to use a knit flutter you will need to import the package hive underscore flatter so make sure that you have it in your dependencies right above the code then once you do that you will see that the error will disappear and at this point we can actually register our type adapter so we use hype.registeradapter and we passed the movie adapter that we created a few minutes ago then we can use hive.openboxer in order to create the box that we're gonna use to store the movies anyhow we will call it favorite movies and we're also gonna specify that this box can only contain the movie object then we can go to our home screen and inside our init state we are going to create a variable that will store the box so that we can actually use the box from the different widget inside the build method so we use a hack.box and we'll pass the name of the boxer let's save this inside the movies box variable actually we also need to define this movie's box variable so let's use the keyword to specify that this variable will have a delayed initialization and then let's specify that this is going to be a box of movies now let's also print the values that are stored inside of the box movies so that we can see now debug console which are the values that are inside this box so let's start restart and as we do that now you can see that the list is completely empty and obviously we have not added anything yet so that's how it is supposed to be now let's scroll down and let's go inside our floating action button at this point inside the show model bottom sheet method we're gonna add the movies box as an input then we can continue scrolling down and we need to actually make sure that this input is required and is a type box now we can scroll down and go inside the elevated button and here first we're gonna create a new movie object and then we're gonna use our movie box and we're gonna use the put method in order to add the movie inside our hive boxer here we need to specify a key which is gonna be the movie id and then also the object that we're gonna save now let's try to add a new movie so let's write the name and then let's go and get a picture of a movie i'll copy the image address and i'm gonna paste it here inside the image url text form field once we save it you can see the movie inside our movies list if we have to start the movie will disappear from the screen because we are still not taking the movies from the hive boxer however if you look at the back console the movie is actually saved inside the hive boxer now we will update the ui soon so that we fetch the data from the boxer however first let me show you another way in order to add movies inside the boxer you can use the add method which will give you the same result however here you don't need to specify the key and the key will be automatically created by hive now let's go back inside the ui and let's start to update our list view builder here first of all we need to wrap it with the value listenable builder then we pass a value listenable and in this case we're gonna listen to the value that are inside the movieboxer so we need to use moviebox.listenable now make sure that you are importing hive underscore flatter otherwise it will not work once you do that the movies.listenable will work fine and we are gonna keep listening to the updates inside the movie boxer now let's prepare the builder and here we're just gonna return the list view that we are showing down below so let's remove child and let's add the return keyword now let's fix the parenthesis now the first thing that we need to do is to create a new variable that we will call movies this is gonna be a list of movies object and basically we're gonna take the values from the box and we're gonna cast them as a list then we also need to use the cast method in order to specify that all the objects are moving now let's go up and let's remove the original list that we were using before because we will not use it anymore so now when you look at the item count the movies is not referring to the original list but it's referring to this movie list which come from our boxer now we can also scroll down and go inside the show model bottom sheet and we can remove the set state because we will not use it anymore and now as we have to start you can see that the movie that we added before is shown on the screen and this is because it was saved into our hive database now if we try to add a new movie let's add the image url and you can see that as soon as we press save the movie is shown on the screen now if we try to click on the icon buttons you can easily notice that nothing happened obviously this is because we have not added anything inside on press so let's change it now so let's take the first icon button and let's use moviesbox.put in order to update the movie object at a specific key so we're gonna pass the key and then we're gonna pass the new value of the movie object essentially we're gonna take the old movie objective we're gonna use the copy with method in order to update the add to watchlist parameter and we're just gonna save it inside our hive box and replace the old one now as soon as we click on the icon you can see that the color is changing because the value of the added to watch list boolean is actually changing as well now let's try to close the app and let's try to restart if we did not implement hive now as soon as the app restarted you would have not seen any movies however we are persisting the data thanks to hive and that's why you can see the two elements that we added before now let's continue and let's try to edit the movie name and the movie image url to do so let's go inside our second icon button and let's pass the show model bottom sheet method here we're gonna add another input which is the movie object now inside the show model volume sheet this is an optional parameter and inside the method we're gonna check if it has been added in fact you can see this if statement and in case it's not null we're gonna set the value of the controller text equal to the movie name and to the movie image url so that basically every time you open the model bottom sheet you will see the current name and the current image url already added into the text field as an initial value now after we click on save you can see that we are adding a new movie inside the list and that's not the desired outcome of this we need to edit an existing movie to change that we need to go down below inside the elevated button and we need to add a little bit of conditional logic now we are always creating a new object and we are adding inside the movie boxer however we need to check whether we are passing an existing movie object inside the metadata and if we are doing that we are just going to update the existing movie so in the if statement we're gonna use movies.puta we're gonna take the specific idea of the movie so the key and then we're using the copy with method to edit and create a new object based on the old one and we're just gonna change the text and the name based on the new input inside the text form fields now instead if this the condition is not true we're gonna have the health statement and here we're gonna create a new movie and we're gonna add it into the box so basically this is for when we want to create a new movie object perfect now let's try to edit if we add movie name we save you can see that we are just editing the existing one and we didn't add a new one now let's also edit the last icon button so that we can also delete the movies from the boxer so here we're going to use box dot delete very simple we just need to pass a key which in this case is going to be the movie id and now if we click on the left button you can see that the movie disappear and it's also going to be removed from the boxer in fact now if we close the app as soon as the app restart those two movies that we just deleted are not gonna show up because they're not gonna be included inside the movies box anymore and in fact you only see the first one and this is how you implement hive in your flutter apps however we can clean up the code and we can also use the block pattern in order to manage everything including our ui and our data coming from the hive database now first of all let's create a blocks folder here we're gonna create a new block and we're gonna call it movie block let's also rename the folder so that it matches the name of our block and then we can start to create a new file in which we're gonna store all the crude operation that we will perform on our hive database so let's create this hive database class and first of all we are going to create a variable a string in which we are going to store the box name in this case we are going to keep the same box name as we did in the main. then we are going to prepare multiple methods the first one is gonna be open boxer then we're gonna have the get movies method and also the add movie method so basically there's gonna be one method for each crude operation one is gonna be the update movie method and finally we're gonna have the let movie method as well but actually let's also add the let all movie so we can either delete one movie or all the demo let's go back to the first method and this is gonna return a boxer and this is gonna be a synchronous so let's add the synchronous keyword and let's start to prepare the body here we're just gonna await hive.open boxer we're gonna specify which box we want to open and we're also gonna specify that this is a box of movie object and finally we're just gonna return the boxer once we use the open box we can return the box and then we can interact with the boxer and perform any of the other crude operation so let's start to develop the get movies this will take the box as an input and the same is required for all the other methods in fact we'll pass this as an input in all of them now let's go back to the body of the get movies method and let's return box dot values then we're gonna make sure that this is gonna be a list and then we need to cast each value inside this list to a movie and now that's pretty much it we're just gonna return the movies and we can use them in our app now let's continue with the add movies and here we just need to use box.put we need to specify the key and we need to pass which object we need to add inside the boxer so this need to be an input for the method and pretty much that's pretty similar compared to what we were doing inside the ui before now the only difference is that we are not going to do it in the ui anymore but we are going to use this class in order to perform all these screw operations now let's do the same for update movies and this is going to be exactly the same as add movies it's just that we're gonna use it in a different situation then to delete the movie we're gonna use await box dot delete and we're just gonna pass the key to indicate which movie we need to delete instead for the last one we're gonna use box.clear and this will remove all the movies from the boxer so basically our box will be empty now we can go back to our window data and we can start to create our hive database variable here so we're gonna use hive database and we're gonna create this instance of the class then we're gonna use hive database dot open box in order to open the box so we can remove the line that we added above because from now on we're only gonna use our hi database class let's pass this as an input into our app and we also need to make it required inside my app widget so we're gonna create the variable we're gonna call it underscore hive database and then we're gonna make it required inside the constructor now let's assign the input to the internal variable and then we're good to go with my app widget we can close the hive database file and we can start to prepare our block inside the movie state we're gonna have two different states so the movie loading and the movie loaded state inside the movie loaded state we're gonna store a variable which is at least a movie and we're gonna call it movies here we're gonna store all the movies that we're gonna show on the screen so let's prepare the constructor and let's make the variable required now we just need to add the props and we need to pass the movies variable inside the props list now we can continue and we can develop the events now we're gonna have one different event for each of the crude operation that we can perform on our hive database so we're gonna have an event wad an event to remove an event to update in an event to load all the movies now we're good to go we can continue to the movie block first of all we need to register an event handler for each of the events that we just created inside the movie event file so the first one is gonna be the loading movies then we're gonna have the update movie add movie and the little movies and finally also the let movie now for each of these we're gonna need to have one different method which will be invoked by the hand handler now let's start to prepare all the logic so in the load movies first of all we're gonna wait for a second to use future.delayed we're gonna use the duration widget and we're gonna pass one second so we wait for a second to simulate some loading time and connection from the database and now we need to import the hive database here inside the movie block we're gonna make here required inside the constructor and then we can continue in this way we can actually access the hive database from each of these methods that we are developing so inside the unload movies we're gonna open the box where we are storing all the movies and objects and then we're gonna get all the movies using the method that we created in our hive database service finally once we retrieve all the movies we're just gonna emit a new movie loaded state and we're gonna display all the movies on the screen now in each of the method we will need to open the boxer so let's just copy hivedatabase.open box into all of the different methods that we have here and let's save this into the box variable now let's continue with the on update movie method here first of all we check whether the state is equal to movie loaded in that case we're gonna use our hive database class and we're gonna use the update movie method we're gonna pass the box and we're gonna pass the specific movie that we want to update and after that we're just going to emit a new state with the movie loaded state in which we pass a new list to movie and this list is going to be updated because it comes directly from our hive database because we're going to use get movies and we're going to retrieve the latest version of the movies we can just copy and paste the update movie method inside the add movie because it's gonna be pretty much the same we're just gonna change update movie with add movie and finally we can create the remaining two methods which are gonna be used in order to delete movie from the database in the first one we're going to use hivedatabase.they let all movies so it's gonna completely empty the list of movies so it's gonna be empty and we're not gonna see any movie on the screen anymore and finally in the last one we're gonna check if the state is moving loaded and then we're gonna use high database.let movie and we're gonna pass one specific movie that we want to delete from the list finally after we delete the movie we will just emit a new movie loaded state and that's pretty much all we need to develop inside the block so we can continue and we can actually create an instance of the block and to do so we will need to wrap the material up with a block provider then inside the block provider we're gonna pass the movie block and here we need to pass the hive database as an input so let's wrap the block provider with a repository provider and we're going to pass repository provider.value we're going to select the hive database and then we're going to be able to use the instance of our repository that we created above inside our block now as soon as we create a block we also add an event and this is going to be the load movie event now in order to use the block we can go inside the home screen and we will need to wrap the value listenable builder with a block builder here we're going to select the movie block and then first of all if the state is movie loading we're just going to show a circular progress indicator else if if the state is movie loaded we're just going to show the same widget that we're showing as of now on the screen and finally we are going to also have the fallback scenario in which we just show a text widget if we have any error in the app now we need to make some changes because we will not need the value listenable builder anymore in fact we have already moved all the logic to retrieve the value from the box from the widget to the block and the hive database service so we won't need it anymore here and we can just retrieve the movies directly from the blocker so we can use state.movies and we're gonna fetch the list of movies coming from the blocker now instead of referring to moviesbox.put we can just add an event to the blocker so we're going to use context.reader we're going to read the movie blocker and we're going to add an update move event and this will take the movie as an input and we're also going to use the copy with method in order to edit the value of the added to watchlist variable so we're not referring anymore to the movies boxer but again we can just add an event in order to perform any crude operation based on what we want to do now we also don't need anymore the stateful widget so we can remove this piece of code and we can convert the stateful widget into a stateless widget now let's continue and the first thing that we do is to check whether the icon button still works as before as you can see if we click we are going to update the added to watch list value so everything seems to be working fine now let's continue and let's prepare the icon button that we are using to delete the movie so here we're gonna use context.read and we're gonna add at the let move event we're just gonna take the movie from the state of the block we're gonna pass the index and this will remove the movie from the list and we can actually test it right now so if you click on the delete button you will see the movie disappearing now we don't need anymore to pass the movies box into the show model bottom sheet method because we are actually using the movie box directly inside the block so we don't need to pass it anymore here and finally let's go inside the elevated button and again we don't need to use the movies box anymore but we're just gonna add an event to the block so in this case in the first scenario we are updating the movie so we're gonna use contact to read and we're gonna add an update movie event we're gonna pass the movie and we can continue now we can delete the old code and inside the else statement we are not going to use update movie anymore because in this case we are adding a new movie to our hive database so we're going to add an add movie event and we're just going to pass the movie object that we are creating right above perfect so these were fine and now we don't have errors anymore so actually right now we can test it for real so the the let button work fine if i hot restart you will not see any movie on the screen because we just deleted the only one and if we try to add a new one i'll add let's say i will add the third one here on rotten tomatoes i'm gonna write the name and then i'm gonna paste the image url and as soon as i save you can see that the movie show up on the screen if we try to edit the title it will work just fine as before and we can also press the other buttons so we can delete it and we can continue now we just need to make a few more changes because in the app bar we have the icon button to remove all the movie from the list so here we will need to use context or read and we're gonna use the event delete all movies so when we click on that we're gonna clean up the list and all the movies are gonna disappear now if i close the app and i open the app again you will see that there's not gonna be no movie at all in the screen because we just deleted all the demo and that's pretty much all that we need to see in this video so you learn how to use hive and also you learn how to use hive together with the block pattern so that's it thanks for watching and stay tuned for the next one
Info
Channel: Max on Flutter
Views: 8,685
Rating: undefined out of 5
Keywords: flutter hive, hive database, hive database flutter, hive flutter, hive tutorial, flutter database, flutter hive tutorial, flutter hive nosql database, flutter nosql, flutter hive nosql, local database flutter, flutter persistent storage, hive nosql, hive db flutter, hive open box, flutter hive bloc, hive tutorial flutter, nosql database in flutter
Id: 1jXzn262WEY
Channel Id: undefined
Length: 24min 37sec (1477 seconds)
Published: Tue Mar 29 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.