migrate method

MigrationResult migrate({
  1. required int fromVersion,
  2. required Map<String, dynamic> payload,
  3. MigrationContext? context,
})

Migrates payload from fromVersion to latestVersion.

Implementation

MigrationResult migrate({
  required int fromVersion,
  required Map<String, dynamic> payload,
  MigrationContext? context,
}) {
  final migrationContext = context ?? const MigrationContext.none();
  if (fromVersion > latestVersion) {
    throw StateError(
      'Save schema $fromVersion is newer than latest $latestVersion.',
    );
  }
  if (fromVersion == latestVersion) {
    return MigrationResult(version: fromVersion, payload: payload);
  }

  final migrationsByFrom = {
    for (final migration in _migrations) migration.from: migration,
  };

  var currentVersion = fromVersion;
  var currentPayload = Map<String, dynamic>.from(payload);

  while (currentVersion < latestVersion) {
    final migration = migrationsByFrom[currentVersion];
    if (migration == null) {
      throw StateError('Missing migration from $currentVersion.');
    }
    final nextPayload = migration.apply(
      Map<String, dynamic>.from(currentPayload),
      migrationContext,
    );
    currentPayload = Map<String, dynamic>.from(nextPayload);
    currentVersion = migration.to;
  }

  return MigrationResult(version: currentVersion, payload: currentPayload);
}