Don't miss ourDecember livestream, with updates on Flutter and live Q&A!
Persist data with SQLite
How to use SQLite to store and retrieve data.
This guide uses thesqflite package. This package only supports apps that run on macOS, iOS, or Android.
If you are writing an app that needs to persist and query large amounts of data on the local device, consider using a database instead of a local file or key-value store. In general, databases provide faster inserts, updates, and queries compared to other local persistence solutions.
Flutter apps can make use of the SQLite databases via thesqflite plugin available on pub.dev. This recipe demonstrates the basics of usingsqflite to insert, read, update, and remove data about various Dogs.
If you are new to SQLite and SQL statements, review theSQLite Tutorial to learn the basics before completing this recipe.
This recipe uses the following steps:
- Add the dependencies.
- Define the
Dogdata model. - Open the database.
- Create the
dogstable. - Insert a
Doginto the database. - Retrieve the list of dogs.
- Update a
Dogin the database. - Delete a
Dogfrom the database.
1. Add the dependencies
# To work with SQLite databases, import thesqflite andpath packages.
- The
sqflitepackage provides classes and functions to interact with a SQLite database. - The
pathpackage provides functions to define the location for storing the database on disk.
To add the packages as a dependency, runflutter pub add:
flutter pub add sqflite pathMake sure to import the packages in the file you'll be working in.
import'dart:async';import'package:flutter/widgets.dart';import'package:path/path.dart';import'package:sqflite/sqflite.dart';2. Define the Dog data model
# Before creating the table to store information on Dogs, take a few moments to define the data that needs to be stored. For this example, define a Dog class that contains three pieces of data: A uniqueid, thename, and theage of each dog.
classDog{finalintid;finalStringname;finalintage;constDog({requiredthis.id,requiredthis.name,requiredthis.age});}3. Open the database
#Before reading and writing data to the database, open a connection to the database. This involves two steps:
- Define the path to the database file using
getDatabasesPath()from thesqflitepackage, combined with thejoinfunction from thepathpackage. - Open the database with the
openDatabase()function fromsqflite.
In order to use the keywordawait, the code must be placed inside anasync function. You should place all the following table functions insidevoid main() async {}.
// Avoid errors caused by flutter upgrade.// Importing 'package:flutter/widgets.dart' is required.WidgetsFlutterBinding.ensureInitialized();// Open the database and store the reference.finaldatabase=openDatabase(// Set the path to the database. Note: Using the `join` function from the// `path` package is best practice to ensure the path is correctly// constructed for each platform.join(awaitgetDatabasesPath(),'doggie_database.db'),);4. Create thedogs table
# Next, create a table to store information about various Dogs. For this example, create a table calleddogs that defines the data that can be stored. EachDog contains anid,name, andage. Therefore, these are represented as three columns in thedogs table.
- The
idis a Dartint, and is stored as anINTEGERSQLite Datatype. It is also good practice to use anidas the primary key for the table to improve query and update times. - The
nameis a DartString, and is stored as aTEXTSQLite Datatype. - The
ageis also a Dartint, and is stored as anINTEGERDatatype.
For more information about the available Datatypes that can be stored in a SQLite database, see theofficial SQLite Datatypes documentation.
finaldatabase=openDatabase(// Set the path to the database. Note: Using the `join` function from the// `path` package is best practice to ensure the path is correctly// constructed for each platform.join(awaitgetDatabasesPath(),'doggie_database.db'),// When the database is first created, create a table to store dogs.onCreate:(db,version){// Run the CREATE TABLE statement on the database.returndb.execute('CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',);},// Set the version. This executes the onCreate function and provides a// path to perform database upgrades and downgrades.version:1,);5. Insert a Dog into the database
#Now that you have a database with a table suitable for storing information about various dogs, it's time to read and write data.
First, insert aDog into thedogs table. This involves two steps:
- Convert the
Doginto aMap - Use the
insert()method to store theMapin thedogstable.
classDog{finalintid;finalStringname;finalintage;Dog({requiredthis.id,requiredthis.name,requiredthis.age});// Convert a Dog into a Map. The keys must correspond to the names of the// columns in the database.Map<String,Object?>toMap(){return{'id':id,'name':name,'age':age};}// Implement toString to make it easier to see information about// each dog when using the print statement.@overrideStringtoString(){return'Dog{id:$id, name:$name, age:$age}';}}// Define a function that inserts dogs into the databaseFuture<void>insertDog(Dogdog)async{// Get a reference to the database.finaldb=awaitdatabase;// Insert the Dog into the correct table. You might also specify the// `conflictAlgorithm` to use in case the same dog is inserted twice.//// In this case, replace any previous data.awaitdb.insert('dogs',dog.toMap(),conflictAlgorithm:ConflictAlgorithm.replace,);}// Create a Dog and add it to the dogs tablevarfido=Dog(id:0,name:'Fido',age:35);awaitinsertDog(fido);6. Retrieve the list of Dogs
# Now that aDog is stored in the database, query the database for a specific dog or a list of all dogs. This involves two steps:
- Run a
queryagainst thedogstable. This returns aList<Map>. - Convert the
List<Map>into aList<Dog>.
// A method that retrieves all the dogs from the dogs table.Future<List<Dog>>dogs()async{// Get a reference to the database.finaldb=awaitdatabase;// Query the table for all the dogs.finalList<Map<String,Object?>>dogMaps=awaitdb.query('dogs');// Convert the list of each dog's fields into a list of `Dog` objects.return[for(final{'id':idasint,'name':nameasString,'age':ageasint}indogMaps)Dog(id:id,name:name,age:age),];}// Now, use the method above to retrieve all the dogs.print(awaitdogs());// Prints a list that include Fido.7. Update aDog in the database
# After inserting information into the database, you might want to update that information at a later time. You can do this by using theupdate() method from thesqflite library.
This involves two steps:
- Convert the Dog into a Map.
- Use a
whereclause to ensure you update the correct Dog.
Future<void>updateDog(Dogdog)async{// Get a reference to the database.finaldb=awaitdatabase;// Update the given Dog.awaitdb.update('dogs',dog.toMap(),// Ensure that the Dog has a matching id.where:'id = ?',// Pass the Dog's id as a whereArg to prevent SQL injection.whereArgs:[dog.id],);}// Update Fido's age and save it to the database.fido=Dog(id:fido.id,name:fido.name,age:fido.age+7);awaitupdateDog(fido);// Print the updated results.print(awaitdogs());// Prints Fido with age 42. Always usewhereArgs to pass arguments to awhere statement. This helps safeguard against SQL injection attacks.
Do not use string interpolation, such aswhere: "id = ${dog.id}"!
8. Delete aDog from the database
# In addition to inserting and updating information about Dogs, you can also remove dogs from the database. To delete data, use thedelete() method from thesqflite library.
In this section, create a function that takes an id and deletes the dog with a matching id from the database. To make this work, you must provide awhere clause to limit the records being deleted.
Future<void>deleteDog(intid)async{// Get a reference to the database.finaldb=awaitdatabase;// Remove the Dog from the database.awaitdb.delete('dogs',// Use a `where` clause to delete a specific dog.where:'id = ?',// Pass the Dog's id as a whereArg to prevent SQL injection.whereArgs:[id],);}Example
#To run the example:
- Create a new Flutter project.
- Add the
sqfliteandpathpackages to yourpubspec.yaml. - Paste the following code into a new file called
lib/db_test.dart. - Run the code with
flutter run lib/db_test.dart.
import'dart:async';import'package:flutter/widgets.dart';import'package:path/path.dart';import'package:sqflite/sqflite.dart';voidmain()async{// Avoid errors caused by flutter upgrade.// Importing 'package:flutter/widgets.dart' is required.WidgetsFlutterBinding.ensureInitialized();// Open the database and store the reference.finaldatabase=openDatabase(// Set the path to the database. Note: Using the `join` function from the// `path` package is best practice to ensure the path is correctly// constructed for each platform.join(awaitgetDatabasesPath(),'doggie_database.db'),// When the database is first created, create a table to store dogs.onCreate:(db,version){// Run the CREATE TABLE statement on the database.returndb.execute('CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',);},// Set the version. This executes the onCreate function and provides a// path to perform database upgrades and downgrades.version:1,);// Define a function that inserts dogs into the databaseFuture<void>insertDog(Dogdog)async{// Get a reference to the database.finaldb=awaitdatabase;// Insert the Dog into the correct table. You might also specify the// `conflictAlgorithm` to use in case the same dog is inserted twice.//// In this case, replace any previous data.awaitdb.insert('dogs',dog.toMap(),conflictAlgorithm:ConflictAlgorithm.replace,);}// A method that retrieves all the dogs from the dogs table.Future<List<Dog>>dogs()async{// Get a reference to the database.finaldb=awaitdatabase;// Query the table for all the dogs.finalList<Map<String,Object?>>dogMaps=awaitdb.query('dogs');// Convert the list of each dog's fields into a list of `Dog` objects.return[for(final{'id':idasint,'name':nameasString,'age':ageasint}indogMaps)Dog(id:id,name:name,age:age),];}Future<void>updateDog(Dogdog)async{// Get a reference to the database.finaldb=awaitdatabase;// Update the given Dog.awaitdb.update('dogs',dog.toMap(),// Ensure that the Dog has a matching id.where:'id = ?',// Pass the Dog's id as a whereArg to prevent SQL injection.whereArgs:[dog.id],);}Future<void>deleteDog(intid)async{// Get a reference to the database.finaldb=awaitdatabase;// Remove the Dog from the database.awaitdb.delete('dogs',// Use a `where` clause to delete a specific dog.where:'id = ?',// Pass the Dog's id as a whereArg to prevent SQL injection.whereArgs:[id],);}// Create a Dog and add it to the dogs tablevarfido=Dog(id:0,name:'Fido',age:35);awaitinsertDog(fido);// Now, use the method above to retrieve all the dogs.print(awaitdogs());// Prints a list that include Fido.// Update Fido's age and save it to the database.fido=Dog(id:fido.id,name:fido.name,age:fido.age+7);awaitupdateDog(fido);// Print the updated results.print(awaitdogs());// Prints Fido with age 42.// Delete Fido from the database.awaitdeleteDog(fido.id);// Print the list of dogs (empty).print(awaitdogs());}classDog{finalintid;finalStringname;finalintage;Dog({requiredthis.id,requiredthis.name,requiredthis.age});// Convert a Dog into a Map. The keys must correspond to the names of the// columns in the database.Map<String,Object?>toMap(){return{'id':id,'name':name,'age':age};}// Implement toString to make it easier to see information about// each dog when using the print statement.@overrideStringtoString(){return'Dog{id:$id, name:$name, age:$age}';}}Unless stated otherwise, the documentation on this site reflects Flutter 3.38.1. Page last updated on 2025-10-30.View source orreport an issue.