Database Storage in Flutter using SQFlite
HTML-код
- Опубликовано: 30 июл 2024
- Persistent data storage is an important topic in mobile development. Both Android and iOS can take advantage of SQLite, a lightweight SQL database. Sqflite is flutter library to tap into that power on both platforms. This tutorial will walk you through the basic CRUD data operations (Creating, Reading, Updating, and Deleting) using the Sqflite library.
00:00 - Intro
00:36 - Reviewing initial code without Sqflite
04:52 - Creating and opening the database using the Singleton pattern
14:00 - Mapping your database column names to your model fields and vice-versa
17:57 - Writing a function to retrieve all rows from a database table and mapping the results to the model
21:47 - Writing a function to insert a row into the database
23:38 - Retrieving all rows of the table when the list widget initializes and setting the bloc data
26:30 - Inserting a new row and updating the bloc data
29:13 - Test inserting foods and debugging
31:22 - Writing a function to delete a row(s) in the database
33:15 - Writing a function to update a row(s) in the database
34:57 - Deleting a food from the database and updating the bloc
37:39 - Updating an existing food in the database and updating the bloc
💻Get the Code: github.com/theflutterfactory/...
⚡Connect on Facebook: / flutterfactory
⚡Connect on Twitter: / flutterfactory
Music: www.bensound.com
What other data storage solutions are you interested in? I may do a 2nd part for this topic that goes into more advanced topics like complicated data structures, batch transactions, etc. Depends on how much interest there is for it.
I'm interested.
One thing I am trying to figure out, is when the database is created i would like to have it pre populated with data, and then it would be possible for the user to update that data. I want to create a workout app, but I want the app to start with four exercises, of which the user can change the rep max and the name of the exercise, but there always need to be only four of these exercises. I was thinking they need to be added when the database is first created, and then only give the options to update them, but not sure how exactly to do this?
Also another thing i think would be useful, is that a user can created say a workout name on one page, and then he goes to another page and adds exercises, and they only then show from the page created before, and they should beable to create another workout with different exercises they would choose to add. I am thinking I would need to create two databases, but then it is how to link certain created exercises to their workout title page, so that when i different workout is created it shows only the created exercises for that workout. To go into something like this I think would be very useful.
i figured out how to pre populate the data, and only once, just put it where you originally open database
nice tutorial, will be interested in the moor data storage solution. Thanks
i would like tutorial about moor database, that show how to connect moor, register,login and crud. Its a good / great advantage if there's about geolocation and how to save the longitude and latitude to moor database.
we are wait to part two
Thank you for these videos. I am so glad its current as well. Going to go through most of them. Thanks
Thank you for a great example of using SQLite database in Flutter
Thank you for this explanation, it was very useful to write down a part of the code for my dissertation!
have been searching for a video that explains this perfectly... saving Bool to database and retrieving it... thanks 👍
Thanks for your video, it was helpful
I am trying to combine a Sqflite database with the table_calendar flutter package. In order to get only the events from each day, I need a Map data structure. Now I know, that the data saved within the Database can be recalled as a List. How would you pass the data to the Map and show the objects within the ListView widget?
many thanks
Can I ask why your insert fucntion returns a type of Future rather than Future?
@Cheetah Coding Could you let us know what the issue is where the sqlite items on ListTile do not update after a page change? They update when you update with button, but after the page is changed, they return to the original value. Thank you!
Hello thanks for the great tutorial... as I am new to flutter I got idea about sqlite database....
BUT
I have one query.
I have prepared database with 500+ entries and I have to do CRUD operation.
So where I should put my data in flutter app so it will work on both iOS and Android... and how to set path of database... in my case..
A word of reply will be highly appreciated.
Thanks sir.
if would like to generate a PDF from Bloc Data using package:pdf but i dont know to acces the data right to use pdf.Table.fromTextAray. Maybe someone can help me ?
Hey Curry! Awesome video! I'm so grateful I came across your channel! Thanks very much for the detailed tutorial. It's really useful to new coders like me! I have a question: When I enter a food item into the list then subsequently edit the values, why are the edited values not stored permanently in the database? Each time I close and reopen the app the initial values ( prior to editing the calories for example) are retrieved. I tried this with your source code and seem to get the same results. Have I done something wrong?? Thanks in advance!
how can i export the sqflite database to external phone storage in flutter???
Thanks Bro...
Thank you. so much. sub! like ! button pressed~!!~!
😍
Thank you for the video. After recent updates to the bloc, I'm having trouble initializing it in main.dart though.
Are you getting an error?
Are you using the exact same version numbers as he has in the video for the dependencies (i.e. flutter_bloc, sqflite, and path)?
I had similar issues as well, then tried this and a lot of the issues went away. For example, the current flutter_bloc version (as of writing this) is '5.0.1'. However, you need to have flutter_bloc version '3.2.0 or it won't load properly.
Great vid thanks a lot! Helps alot in developing my first app. Appreciate if you could show how do we do a search and filter data in an sqflite database.
Good tutorial! quick question though, where would you add the code to fill the database first time opening the app?
That's up to you. The getFoods method is only called when the app is launched. You could just add the code in the initState method of your first screen if the data is coming from an api call
Is there a video showing you building the initial code ?
i have a problem with this, its not updating
Can u tell me how much storage we can use in flutter??
Well thanks for the tutorial, it is really helpful but i would like to ask why you call the databaseProvider.db by yourself? after you .add(Event) FoodBloc should call the databaseProvider and Inset or Update regarding to the Event you add. Isn't it the reason we have Bloc ?
I didn't really think about architecture much with this video. I just focused on the DB info. If I were to do this video again, I would probably add repository between the Bloc and the database provider in the initial code.
Thanks for the video. A suggestion to make future tutorials a little more beginner friendly: Could you please have the initial source code (in this instance, prior to sqflite, but with BLoC) in a clearly marked archive folder within the project files? It wasn't very clear at the start where the initial source code was starting from. E.g. Was the code simply continuing from where your BLoC tutorial finished? While the start of the video seemed to imply that, I noticed a number of differences between the completed code in your BLoC tutorial and the code you were showing at the start of the video.
In the end, I realised I had to dig around for the previous versions of the code in github. Many beginners will not realise this, and will get frustrated since simply getting to the starting line with your tutorial is such a scavenger hunt.
Some good points in there. I don't really plan everything out long term since this isn't any type of structured course and I'm essentially doing all this for free in my spare time. This is one of the few videos I did that build upon code from a previous video. I'll try to make things more clear in the future. Appreciate the feedback.
Neatly explained and easy to follow. Had a question to follow this video. If at all we need to add 'Favourites' will that mean it is a new event?
It can be. That's up to you.
Hello, i am a uix designer and for my thesis I need to translate my concept into a real working prototype. I have the basic (really basic) of Javascript, will it be a challenge to learn how to create my concept (using Firebase database/ OCR ML kit?
That's an impossible question for me to answer. It depends on many factors like how many fundamental concepts of software development you already understand, the time frame of your project, and the complexity of your project.
is there a benefit to separating the event classes?
"Separation of Concerns" makes code easier to manage. If I want to change event code, I know exactly where i need to look. I can also use that same event in multiple places as the app grows.
Hello curry your courses are great but I can't follow along because you don't start from scratch. Am a self taught developer so most times I depend on RUclips videos. But always start your tutorials from scratch so that beginners can easily follow along. Thank you
I can't start every video from the beginning. There would be way too much repetition and all the videos would be too long. This video is about Sqflite only so that's what i focus on. This video assumes that you already know the very basics of flutter (Scaffolds, Stateless/stateful widgets, etc). You can look at the earlier flutter videos i did if you don't understand those concepts.
Hey your video has been really helpful but can you pleaseeeeeeeeeeeee make a video on how to create more than one table in the database!!!! 😅😅😅 It would be really helpful thanx :)
But, where is the db located on the real device or the simulator? I want to change the structure and tables outside the flutter app but I cant find the file
What do you mean change the database from "outside" the flutter app. It would be extremely bad for security if someone was allowed to alter the database from outside of the app itself. Are you talking about prepopulating the database?
@@TheFlutterFactory Thank you for your reply. I want to be able to find and open the sqlite database using sqliteStudio for example and fill it from csv. I have been searching the .sqlite file inside the app folder, the emulator folder and in the real device but I still cannot find it to edit
It doesn't seem to update. It does when app running, but when close it and reopen the updated data is not there only the originally created data.
I had the same problem. I add inside the new food object the old id (id from the food object) and then change the parameter in the DatabaseProvider from widget.food to food.
@@jowet1722 would be nice if OP could make update to his Github code
@@jowet1722 Could you please be a bit more precise on what you did? I am not sure how to make it update. Thank you!
@@teemoisbaron3638 Oh. I'm so sorry. I totally forgot how I solved that issue. Next time I will be more specific
@@jowet1722 Thanks anyway man, I just can't figure out what's the issue.
It would be nice to see a tutorial on how to backup this database to a file and then restore it from a file. So that user can backup the data, delete the app, and then redownload the app and restore the data from file
Agreed
please upload a latest video on sqflite because after updation of flutter this code will not be work on my flutter
which version are you using?
I can't get this to work properly in a tab and not in home, the tab doesn't update automatically
I don't understand the issue. The tab doesn't update what?
@@TheFlutterFactory thanks for your answer. The widget inside the tab isn't updated anymore upon performing the tasks, I have to change tab (bottomnavigationbar) and return to see them updated.
I tried adding a category option in it i don't know what i did wrong but after that it is showing that """Unhandled Exception: DatabaseException(table food has no column named category (code 1 SQLITE_ERROR): , while compiling: INSERT INTO food (name, calories, isVegan, category) VALUES (?, ?, ?, ?)) sql 'INSERT INTO food (name, calories, isVegan, category) VALUES (?, ?, ?, ?)' args [io, 54, 1, Education]}""" I did added column in databaseprovider.dart, food.dart, foodform.dart
Edit:
I tried renaming isVegan with isRandom and i changed everything but still in error it shows isVegan only it is not changing..
I probably should have made a part 2 where I talk about upgrading the DB. Whenever you change a database schema, you need to let SQFlite know that it needs to migrate the schema to a new version. You can follow this guide here. I might actually do a new video about this in the future since it is an import aspect of local databases.
efthymis.com/migrating-a-mobile-database-in-flutter-sqlite/
@@TheFlutterFactory thanks for your reply i really appreciate it and yeah i will try that please make a part 2 though
Why in lib\bloc\food_bloc.dart the name of class FoodBloc is underlined with red color?
I don't know. What does your error say? It should tell you what the issue is.
@@TheFlutterFactory I reopened the project, and this time the error disappeared and everything works correctly, I don't know what was the reason, but now the code is working. I'm just starting to learn Flutter and it's still difficult to deal with databases, there are very few examples in which in one application are used existing SQLite with Images, ListView with search, buttons for adding to favorites
Make video on storing image in sqflite database for flutter
how to add an image to the database?
You can store it as a Blob using an array of bytes, but i wouldn't recommend doing that. Just store the files on the device in the app storage location so it can't be seen in the file explorer apps . I'll probably do a separate video about that in the near future.
30:39
I disagree.
It isn't because you used an arrow function, it is because you access context in the .then of a future called in initState. You cannot guarantee that the context is right. You need to find a better way to call the getFoods. I recomment using a FutureBuilder or, failing that, a Widget Binding Observer.
Yes it seemed to work after you changed it but the problem is that it is timing related.
Hi, do we need any user permission for this to work?
Nope. It's not accessing file storage on the device. It's saving the dB in the app storage location which is a separate entity.
@@TheFlutterFactory Okay, thanks for your response.
can i get the source code for the app?
Read the description 🙂
Did you not realize at the end of your video that after updating the objects, the ID turned into "null"?
I was just focusing on the fields field displayed in the list. That was a while ago so i don't recall the reasoning behind me not doing it. The fix isn't anything complicated. It just involves copying over the ID from the existing food when the new food is created. I'll probably end up redoing these topics for both the react native and Flutter firebase series in sometime in 2020
@@TheFlutterFactory How can i fix it?
I got it.
added:
final int olistid;
OListForm({this.olist, this.olistindex, this.ean, this.olistid});
Then gave it in list.dart to the builder
builder: (context) => OListForm(
olist: olist,
olistindex: index,
ean: olist.ean,
olistid: olist.id,
Idk if anyone can understand this, but i used different vars...
This tutorial looked nice and easy to follow for a beginner until it got to the bloc part. From there it just all fell apart for me...
I will probably do a new video about this topic without bloc within the next couple of months.
@@TheFlutterFactory That would be really helpful. Im completely new to Flutter and SQL and this one went a bit too far for me. I think I should maybe start with Flutter basics. This is only my second coding language and I though things would translate over a bit easier than they did. So I probably just lack too much background.
SQL can be a complicated topic. Using a package like this assumes that you already know the fundamentals of SQL queries/transactions. I would advise that you learn about SQL by itself before trying to use it in a library. This channel also assumes that you already understand the fundamentals of the Dart language and general programming concepts.
@@TheFlutterFactory Yeah, I'll go over more basic stuff first and maybe by the time Im done with that your next video is out already ;)