Opening a sembast database

The first object we'll use is a DatabaseFactory. A database factory allows us to open a sembast database. Each database is a file. Let's look at the steps:

  1. Add the following code under the constructors to create a DatabaseFactory:
DatabaseFactory dbFactory = databaseFactoryIo;
  1. After opening the database, you need to specify the location in which you want to save files. Stores could be considered 'folders' inside the database: they are persistent maps, and their values are the Todo objects. Add the following code to specify the store for our read/write operations:
final store = intMapStoreFactory.store('todos');
  1. Next, we'll open the database itself: first declare a Database object, called _database:
Database _database;
  1. Then add a getter that will check whether the _database has already been set: if it has, the getter will return the existing _database. If it hasn't, it will call the _openDb() asynchronous method, which we will create in the next step. This is a pattern that you can use whenever you need a singleton in your code:
Future<Database> get database async {
if (_database == null) {
await _openDb().then((db) {
_database = db;
});
}
return _database;
}
  1. Now we are ready to write the _openDb() asynchronous method, which will open the sembast database:
Future _openDb() async {}
  1. Inside the openDb() method, we'll get the specific directory where data will be stored: this is platform specific, but as we are using the path library, there's no need to worry about the way the operating system is storing data. Add the following code to retrieve the document directory for your system:
 final docsPath  = await getApplicationDocumentsDirectory();
  1. Next, call the join() method to join the docsPath and the name of the database, which we will predictably call todos.db, into a single path using the current platform's separator. The .db extension is optional:
 final dbPath = join(docsPath.path, 'todos.db');
  1. Finally, using the dbFactory, call the openDatabase() method to actually open the sembast database and return it:
 final db = await dbFactory.openDatabase(dbPath);
return db;

Now that the database is open, we need to write the methods for the create, read, update, and delete tasks. Let's do that next:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.80.45