Created
May 17, 2022 00:32
-
-
Save tytydraco/547d365004cce79e4cb8cb7175335e60 to your computer and use it in GitHub Desktop.
A helper class to handle basic SQLite operations in Flutter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:path/path.dart'; | |
import 'package:sqflite/sqflite.dart'; | |
/// A very simple class that we recognize as SQLite-compatible | |
abstract class DatabaseModel { | |
Map<String, Object?> toMap(); | |
} | |
/// A very simple helper class to manage local SQLite databases. | |
/// It should be adjusted as needed. | |
class DatabaseHelper<T> { | |
static const String databaseFileName = 'deebee.db'; | |
static const int databaseVersion = 1; | |
static const String tableName = 'entries'; | |
static const String tableSchema = 'id INTEGER PRIMARY KEY, age INTEGER'; | |
Future<Database> initializeDB() async { | |
String path = await getDatabasesPath(); | |
return openDatabase( | |
join(path, databaseFileName), | |
onCreate: (database, version) async { | |
await database.execute( | |
"CREATE TABLE $tableName($tableSchema)", | |
); | |
}, | |
version: databaseVersion, | |
); | |
} | |
/// Insert a model into the database | |
Future<int> insert(DatabaseModel model) async { | |
int result = 0; | |
final Database db = await initializeDB(); | |
result = await db.insert( | |
tableName, | |
model.toMap(), | |
); | |
return result; | |
} | |
/// Retrieve all models from the database. | |
/// Specify a function to construct an Object from the returned JSON. | |
Future<List<DatabaseModel>> retrieve(DatabaseModel Function(Map<String, Object?>) mapFunc) async { | |
final Database db = await initializeDB(); | |
final List<Map<String, Object?>> queryResult = await db.query(tableName); | |
return queryResult.map((e) => mapFunc(e)).toList(); | |
} | |
/// Delete an entry where a variable matches a value | |
Future<void> delete(String variable, Object value) async { | |
final db = await initializeDB(); | |
await db.delete( | |
tableName, | |
where: "$variable = ?", | |
whereArgs: [value], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment