Simple SQFlite database example in Flutter

Image for post
Image for post

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:

Image for post
Image for post

Pressing each button will perform the related operation on the database using SQFlite.

For this minimal example, you will do the following steps:

  1. Add the dependencies

Start by creating a new Flutter project called flutter_database.

Dependencies

Open the pubspec.yaml file and add the following lines to the dependencies section:

sqflite: ^1.2.0
path_provider: ^1.5.1

Change the version number to whatever is the most current for sqflite and path_provider.

Database helper

Create a new file in the lib folder and call it database_helper.dart.

Copy in the following code:

App code

Open your main.dart file and replace it with the following code:

Finished

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.

Further reading

A Flutter and Dart developer. Follow me on Twitter @suragch1 to get updates of new articles.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store