Chapters

Hide chapters

Flutter Apprentice

Third Edition · Flutter 3.3 · Dart 2.18.0 · Android Studio 2021.2.1

Section IV: Networking, Persistence and State

Section 4: 7 chapters
Show chapters Hide chapters

Appendices

Section 7: 2 chapters
Show chapters Hide chapters

15. Saving Data With SQLite
Written by Kevin D Moore

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

So far, you have a great app that can search the internet for recipes, bookmark the ones you want to make and show a list of ingredients to buy at the store. But what happens if you close the app, go to the store and try to look up your ingredients? They’re gone! As you might have guessed, having an in-memory repository means that the data doesn’t persist after your app closes.

One of the best ways to persist data is with a database. Both Android and iOS provide access to the SQLite database system. This allows you to insert, read, update and remove structured data that are persisted on disk.

In this chapter, you’ll learn about using the sqflite plugin and the Moor and sqlbrite packages.

By the end of the chapter, you’ll know:

  • How to create SQLite-based databases.
  • How to insert, fetch and remove recipes or ingredients.
  • How to use the sqflite plugin.
  • How to use the sqlbrite library and receive updates via streams.
  • How to leverage the features of the Moor library when working with databases.

Databases

Databases have been around for a long time, but being able to put a full-blown database on a phone is pretty amazing.

What is a database? Think of it like a file cabinet that contains folders with sheets of paper in them. A database has tables (file folders) that store data (sheets of paper).

Column 2 Column 1 Key Table Column 2 Column 1 Key Table Column 1 Column 2 Key Table Database

Database tables have columns that define data, which is then stored in rows. One of the most popular languages for managing databases is Structured Query Language, commonly known as SQL.

You use SQL commands to get the data in and out of the database. In this chapter, you’ll learn about SQL commands that create SQL statements that:

  1. Manage a database.
  2. Manage data in the database’s tables.

Using SQL

The SQLite database system on Android and iOS is an embedded engine that runs in the same process as the app. SQLite is lightweight, taking up less than 500 Kb on most systems.

Writing queries

One of the most important parts of SQL is writing a query. To make a query, use the SELECT command followed by any columns you want the database to return, then the table name. For example:

Adding data

You can add data using the INSERT statement:

Deleting data

To delete data, use the DELETE statement:

Updating data

You use UPDATE to update your data. You won’t need this command for this app, but for reference, the syntax is:

sqflite

The sqflite plugin provides SQLite database access on iOS, Android and macOS. This plugin provides everything you need to handle SQLite databases, but it’s a bit hard to use. Later, you’ll use the Moor package, which makes things easier. First, however, it’s important to learn how to use the underlying plugin.

sqlbrite

The sqlbrite library is a reactive stream wrapper around sqflite. It allows you to set up streams so you can receive events when there’s a change in your database. In the previous chapter, you created watchAllRecipes() and watchAllIngredients(), which return a Stream. To create these streams from a database, sqlbrite uses watch() methods.

Adding a database to the project

If you’re following along with your app, open it and keep using it with this chapter. If not, locate the projects folder for this chapter and open the starter folder.

Lurogq 3 Pulotl 5 Zix Pitne Qikekh 5 Xoyajs 2 Vej Lifhi Duwanb 2 Xidunb 2 Rem Palxu Qugusup Ozhdavoaxzm Puyasete Joholonofh

Adding sqflite

To use the sqflite plugin, open pubspec.yaml and add the following packages after the equatable package:

Setting up the database

In the data folder, create a new folder named sqlite. Inside that folder, create a new file called database_helper.dart. This class will handle all the SQLite database operations.

Creating tables

One of the most important parts of creating a database is creating the tables. Your app will have two tables: recipeTable and ingredientTable.

Opening the database

Before you can use the database, you have to open it. _initDatabase() uses sqflite’s openDatabase(). Such method requires a path where it should create the database, the current database version and a “create” method name.

Converting data to classes

To convert the stored map of data from the database to classes, you’ll need to add fromJson() and toJson() to the model classes.

Implementing repository-like functions

Your next step is to create functions that return the information that the repository expects. That includes finding recipes and ingredients, watching for changes in them and deleting or inserting them into the database.

Finding recipes

After the user has added recipes, they’ll want a quick way to find the one they have in mind for dinner. That’s what you’ll work on next.

Inserting data into tables

The user will want to add the delicious recipes they find to the app. To let them do this, you need a way to insert data into tables.

Deleting data

Deleting data is just as easy as inserting it; you just need the table name and a row ID. You can also use other methods to delete rows based on the names of recipes or other criteria.

Initializing and closing

SQLite databases need to be opened and closed. When you start the app, open the database and, when you are finished with the app or database, close it again.

Adding an SQLite repository

Just like your MemoryRepository, you need a repository class for your database. You’ll create SqliteRepository to fulfill this need.

HekivjKayemuyiyy TmgozoGemezifuwq Dulegiyacl

Setting the recipe’s ID

If the ingredient’s recipeId isn’t set, the database won’t know which ingredient belongs to which recipe.

Inserting the ingredients

Next, you’ll insert the ingredients.

Deleting recipes

Now that you have the delete methods in the helper class, you need to implement them in the repository. Most of these just call the helper’s methods.

Initializing and closing

Remember that databases need to be opened and closed. To do this, your repository just needs to call dbHelper’s methods.

Running the app

After all that work, it’s time to see your changes. For your last change before you run, open main.dart.

Using the Moor Library

As you saw, that was a lot of work. Now that you know how to do things the hard way, you’ll learn how to use an easier method.

Database classes

For your next step, you need to create a set of classes that will describe and create the database, tables and Data Access Objects (DAOs).

Yukra VaducufeEppumrik JuxufiyiAqtojsoj MoewSopite PeogOkchusuiwc HuqoxaHuo EvfbafiovbRie Hubye Nevuzupe XohiyiKacosegu

Creating tables

To create a table in Moor, you need to create a class that extends Table. To define the table, you just use get calls that define the columns for the table.

Defining the Ingredient table

Now, find and replace // TODO: Add MoorIngredient table definition here with:

Creating the database class

Moor uses annotations. The first one you need is @UseMoor. This specifies the tables and Data Access Objects (DAO) to use.

Creating the DAO classes

Your first step is to create the RecipeDao class. You’ll see more red squiggles, just ignore them for now. With moor_db.dart still open, replace // TODO: Add RecipeDao here with the following:

Generating the part file

Now, you need to create the Moor part file. In Terminal, run:

Converting your Moor recipes

At the end of moor_db.dart, replace // TODO: Add moorRecipeToRecipe here with:

Creating classes for Ingredients

Next, you’ll do the same for the ingredients models. Replace // TODO: Add moorIngredientToIngredient and MoorIngredientCompanion here with the following:

Updating watchAllRecipes()

Now that you’ve written the conversion methods, you can update watchAllRecipes().

Creating the Moor repository

Now that you have the Moor database code written, you need to write a repository to handle it. You’ll create a class named MoorRepository that implements Repository:

MegaspFefazupukb KxlanuFekevuluwj RourQiqusixats Mumifumihq

Implementing the repository

As you did in past chapters, you’ll now add all the missing methods following the TODO: indications. Replace // TODO: Add findAllRecipes() with:

Finding recipes

The find methods are a bit easier, but they still need to convert each database class to a model class.

Inserting recipes

To insert a recipe, first you insert the recipe itself and then insert all its ingredients. Replace // TODO: Add insertRecipe() with:

Deleting

Deleting is much easier. You need to call the DAO methods. Replace // TODO: Add Delete methods with:

Replacing the repository

Now, you just have to replace your SQL repository with your shiny new Moor repository.

Running the app

Stop the running app, build and run. Try making searches, adding bookmarks, checking the groceries and deleting bookmarks. It will work just the same as with SqliteRepository. However, notice that when you started the app, it didn’t contain any entries. Do you know why?

Cleaning up (Optional)

In the next chapter you will not need the sqflite plugin now that you’re using Moor. You can delete the unused dependencies and classes defined in the first iteration of the app. Note that this is optional. To do so, delete the folder lib/data/sqlite and all its files. Then open pubspec.yml and remove the following libraries:

Key points

  • Databases persist data locally to the device.
  • Data stored in databases are available after the app restarts.
  • The sqflite plugin requires some SQL knowledge to set up the database.
  • The Moor package is more powerful, easier to set up and you interact with the database via Dart classes that have clear responsibilities and are easy to reuse.

Where to go from here?

To learn about:

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now