No matter who you are or what you do, sooner or later you’re going to need to store data in your app and then retrieve it later. But what should you use to do that? Lewis Cianci checks it out.
There are a lot of options out there today when it comes to databases in your application. They typically fit into these three categories:
By the end of this article, you will know:
In this article, we’ll divide our database types according to the three categories mentioned above.
Relational databases have been around for a very long time (since 1970, according to a quick Google search). Let’s look at some of the options you have on Flutter for relational databases today.
SQflite is an implementation of SQLite for Flutter. It affords you complete control over your database, queries, relationships, everything you could wish for.
Interacting with a SQLite database in Flutter looks like this (
):
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
// Delete the database
await deleteDatabase(path);
// open the database
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
Inserting data follows the same age-old SQLite tenants
// Insert some records in a transaction
await database.transaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
print('inserted1: $id1');
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
print('inserted2: $id2');
});
And querying happens like this:
// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
SQFlite is good when you need relational data but also fine-grained control over the actual queries. If you’re comfortable with writing your own queries and don’t mind writing both a lot of queries and the code to convert the results to and from your classes, this could be a good fit for you.
#database #flutter #developer