sqflite_hooks 1.0.0 sqflite_hooks: ^1.0.0 copied to clipboard
A new flutter plugin project.
sqflite_hooks #
An extension to sqflite for adding hooks to database actions.
Getting Started #
In your flutter project add the dependency:
dependencies:
...
sqflite_hooks: ^1.0.0
sqflite is included as part of this package but if you require a specific version, make sure this is added to your pubspec.yaml
.
For help getting started with Flutter, view the online documentation.
Usage example #
The usage is no different to sqflite. Just be sure to import sqflite_hooks
instead of sqflite
:
import 'package:sqflite_hooks/sqflite_hooks.dart';
Then you can open and create your database like so:
var databasesPath = await getDatabasesPath();
var path = join(databasesPath, 'demo.db');
var database = await openDatabase(path, version: 1,
onCreate: (database, version) async {
await database.execute(
'''CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL);''');
});
Using hooks #
The main difference when using sqflite_hooks
is that you can add hooks to a database object. This allows you to easily run Dart code when actions occur on your database.
database.addHook(
(event) => event.table == 'Users' && event.operation == DatabaseOperation.insert,
(event) {
// do something when a new record is inserted on the Users table
},
'NewUserHook');
The addHook
method is as follows:
void addHook(bool Function(DatabaseEvent) predicate, Function(DatabaseEvent) hook, String key)
- The
predicate
parameter is aFunction
which should returntrue
if thehook
should run. Apredicate
should not be marked asasync
. - The
hook
parameter is aFunction
which will run should thepredicate
return true. Ahook
can beasync
. - The
key
parameter is aString
used for keeping track of hooks and removing them later.
The DatabaseEvent
class contains the following properties:
final DatabaseOperation operation;
final String table;
final Map<String, dynamic> values;
final String where;
final List whereArgs;
The operation
property is a DatabaseOperation
enum which has the following values:
enum DatabaseOperation { insert, update, delete }
Hooks can be removed like so:
database.removeHook('NewUserHook');
Please note: all hooks for a predicate
returning true
will run and be await
-ed before the database operation completes.