tryAddLocalId<T, E> method

Map<T, E> tryAddLocalId<T, E>(
  1. String id, {
  2. required String idFieldName,
  3. required bool tryAddLocalId,
})

This method is used to maintain a local ID field without storing it in the database. It's particularly useful for maintaining document IDs in DTOs and models.

Adds a local ID field to the map if specified conditions are met.

Example:

final data = {'name': 'John'};
final result = data.tryAddLocalId(
  '123',
  idFieldName: '_id',

Parameters:
- [id] The ID to add
- [idFieldName] The field name under which to store the ID
- [tryAddLocalId] Whether to attempt adding the ID

Returns:
A new [Map] with the ID added if conditions are met
  tryAddLocalId: true,
);

Implementation

/// Adds a local ID field to the map if specified conditions are met.
///
/// Example:
/// ```dart
/// final data = {'name': 'John'};
/// final result = data.tryAddLocalId(
///   '123',
///   idFieldName: '_id',
///
/// Parameters:
/// - [id] The ID to add
/// - [idFieldName] The field name under which to store the ID
/// - [tryAddLocalId] Whether to attempt adding the ID
///
/// Returns:
/// A new [Map] with the ID added if conditions are met
///   tryAddLocalId: true,
/// );
/// ```
Map<T, E> tryAddLocalId<T, E>(
  String id, {
  required String idFieldName,
  required bool tryAddLocalId,
}) =>
    tryAddLocalId && containsKey(idFieldName)
        ? this as Map<T, E>
        : (this..[idFieldName] = id) as Map<T, E>;