There are a number of tutorials out there about how to setup a SQLite database in Flutter using the SQFlite plugin. They were helpful but I found myself getting lost in the details. My purpose in this post is to give you a minimal example that you can get through in 10 minutes. Once you have it working, you can go on to some of the more advanced topics in other tutorials.
Here is the minimal app that we will be making:
Pressing each button will perform the related operation on the database using SQFlite.
For this minimal example, you will do the following steps:
- Add the dependencies
- Make a database helper class
- Make your app layout with the button logic
Start by creating a new Flutter project called
Open the pubspec.yaml file and add the following lines to the dependencies section:
Create a new file in the
lib folder and call it database_helper.dart.
Copy in the following code:
Open your main.dart file and replace it with the following code:
That’s it! You should be able to run the app now. Pressed the buttons an watch the logged output from the print statements. (In Android Studio make sure you have the Run tab selected.)
Read back through the code comments to understand what the different parts do. If there is anything that you don’t understand, you can ask in a comment below.
For a production app I would recommend that don’t mix your UI code and your database code. You should have a state management layer to handle events from the UI and a service layer to put your database code in. I describe that in much more detail here:
Flutter state management for minimalists
Architecting your app without complex third-party packages
If you have your architecture set up in that way, it becomes relatively easy to swap out another database solution without breaking your app. Here are some popular alternatives: