importDatabase function Null safety

Future<Database> importDatabase(
  1. Map srcData,
  2. DatabaseFactory dstFactory,
  3. String dstPath,
  4. {SembastCodec? codec,
  5. List<String>? storeNames}
)

Import the exported data into a new database

An optional storeNames can specify the list of stores to import. If null All stores are exported.

Implementation

Future<Database> importDatabase(
    Map srcData, DatabaseFactory dstFactory, String dstPath,
    {SembastCodec? codec, List<String>? storeNames}) async {
  await dstFactory.deleteDatabase(dstPath);

  // check signature
  if (srcData[_exportSignatureKey] != _exportSignatureVersion) {
    throw const FormatException('invalid export format');
  }

  final version = srcData[_dbVersion] as int?;

  final db = await dstFactory.openDatabase(dstPath,
      version: version, mode: DatabaseMode.empty, codec: codec);
  var sembastDatabase = db as SembastDatabase;
  await db.transaction((txn) async {
    final storesExport =
        (srcData[_stores] as Iterable?)?.toList(growable: false).cast<Map>();
    if (storesExport != null) {
      for (var storeExport in storesExport) {
        final storeName = storeExport[_name] as String;

        // Filter store
        if (storeNames != null) {
          if (!storeNames.contains(storeName)) {
            continue;
          }
        }

        final keys = (storeExport[_keys] as Iterable).toList(growable: false);
        final values = List<Object>.from(storeExport[_values] as Iterable);

        var store =
            (txn as SembastTransaction).getSembastStore(StoreRef(storeName));
        for (var i = 0; i < keys.length; i++) {
          await store.txnPut(
              txn, sembastDatabase.fromJsonEncodable(values[i]), keys[i]);
        }
      }
    }
  });
  return db;
}