getNextID method

Future<int> getNextID({
  1. required TablesWithAutoIncrement table,
  2. int? userID,
})

Retrieves the next available ID for auto-incrementing tables.

This method is responsible for generating a new ID for tables that require auto-increment functionality. It ensures that new IDs are unique and, in case of locally created items, it uses negative IDs.

When pushing updates to an online database, the new ID will be returned and replaced accordingly.

  • table: The table for which the next ID is required.
  • userID: Optional userID for future customization.

Returns the next available ID.

Implementation

Future<int> getNextID({required TablesWithAutoIncrement table, int? userID}) async {
  // Ensure the database is ready before any interaction.
  await ensureDBIsInitialized();

  List<Map>? result;

  // Handle ID fetching based on the table provided.
  switch (table) {
    case TablesWithAutoIncrement.users:
      result = await database.rawQuery('SELECT MIN(ID) as currentID FROM users');
      break;
  }

  int nextID = 1; // Default starting ID if no records exist.

  // Increment logic based on the current ID from the table.
  if (result.isNotEmpty) {
    nextID = result.first['currentID'] ?? 0;
  }

  return nextID + 1; // Increment and return next available ID.
}