exportDatabase function Null safety

Future<Map<String, Object?>> exportDatabase(
  1. Database db,
  2. {List<String>? storeNames}
)

Return the data in an exported format that (can be JSONified).

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

Implementation

Future<Map<String, Object?>> exportDatabase(Database db,
    {List<String>? storeNames}) {
  return db.transaction((txn) async {
    var export = <String, Object?>{
      // our export signature
      _exportSignatureKey: _exportSignatureVersion,
      // the db version
      _dbVersion: db.version
    };

    final storesExport = <Map<String, Object?>>[];

    // export all records from each store

    // Make it safe to iterate in an async way
    var sembastDatabase = (txn as SembastTransaction).database;
    var stores = List<SembastStore>.from(sembastDatabase.getCurrentStores());
    // Filter stores
    if (storeNames != null) {
      stores.removeWhere((store) => !storeNames.contains(store.name));
    }
    stores.sort((store1, store2) => store1.name.compareTo(store2.name));

    for (var store in stores) {
      final keys = [];
      final values = [];

      final storeExport = <String, Object?>{
        _name: store.name,
        _keys: keys,
        _values: values
      };

      for (var record in store.currentRecords) {
        keys.add(record.key);
        values.add(sembastDatabase.toJsonEncodable(record.value!));
        if (sembastDatabase.cooperator!.needCooperate) {
          await sembastDatabase.cooperator!.cooperate();
        }
      }

      // Only add store if it has content
      if (keys.isNotEmpty) {
        storesExport.add(storeExport);
      }
    }

    if (storesExport.isNotEmpty) {
      export[_stores] = storesExport;
    }
    return export;
  });
}