How do I open an IndexedDB database with Dart?
The new IndexedDB API uses Dart's support for Streams and Futures. Here's how you open an IndexedDB database with Dart M3 or greater:
import 'dart:html';import 'dart:indexed_db';import 'dart:async';Future<Database> openDatabase(String dbName, String storeName, {int version:1}) { return window.indexedDB.open(dbName, version: version, onUpgradeNeeded: (e) { Database db = e.target.result; if (!db.objectStoreNames.contains(storeName)) { db.createObjectStore(storeName); } });}main() { openDatabase('test-db', 'test-store').then((Database db) { // do database stuff });}
In this code the window.indexedDB.open
call returns a Future<Database>
, which completes when the database is opened.
The onUpgradeNeeded
function is run when the version of the database does not match the version specified.