Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

docs.flutter.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more

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.

Note

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:

  1. Add the dependencies.
  2. Define theDog data model.
  3. Open the database.
  4. Create thedogs table.
  5. Insert aDog into the database.
  6. Retrieve the list of dogs.
  7. Update aDog in the database.
  8. Delete aDog from the database.

1. Add the dependencies

#

To work with SQLite databases, import thesqflite andpath packages.

  • Thesqflite package provides classes and functions to interact with a SQLite database.
  • Thepath package 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 path

Make sure to import the packages in the file you'll be working in.

dart
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.

dart
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:

  1. Define the path to the database file usinggetDatabasesPath() from thesqflite package, combined with thejoin function from thepath package.
  2. Open the database with theopenDatabase() function fromsqflite.
Note

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 {}.

dart
// 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'),);

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.

  1. Theid is a Dartint, and is stored as anINTEGER SQLite Datatype. It is also good practice to use anid as the primary key for the table to improve query and update times.
  2. Thename is a DartString, and is stored as aTEXT SQLite Datatype.
  3. Theage is also a Dartint, and is stored as anINTEGER Datatype.

For more information about the available Datatypes that can be stored in a SQLite database, see theofficial SQLite Datatypes documentation.

dart
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:

  1. Convert theDog into aMap
  2. Use theinsert() method to store theMap in thedogs table.
dart
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}';}}
dart
// 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,);}
dart
// 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:

  1. Run aquery against thedogs table. This returns aList<Map>.
  2. Convert theList<Map> into aList<Dog>.
dart
// 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),];}
dart
// 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:

  1. Convert the Dog into a Map.
  2. Use awhere clause to ensure you update the correct Dog.
dart
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],);}
dart
// 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.
Warning

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}"!

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.

dart
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:

  1. Create a new Flutter project.
  2. Add thesqflite andpath packages to yourpubspec.yaml.
  3. Paste the following code into a new file calledlib/db_test.dart.
  4. Run the code withflutter run lib/db_test.dart.
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}';}}
Was this page's content helpful?

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.


[8]ページ先頭

©2009-2025 Movatter.jp