applyIndex function

dynamic applyIndex(
  1. dynamic value,
  2. String indexStr
)

Applies an index operation to extract a single element from a list

Extracts a single element from a list using 0-based indexing. Supports both positive indices (from start) and negative indices (from end).

Parameters

  • value - List or single value to index
  • indexStr - Index as string (e.g., '0', '-1', '5')

Index Types

  • Positive: 0-based from start (0 = first, 1 = second, ...)
  • Negative: From end (-1 = last, -2 = second to last, ...)

Returns

  • For lists: Element at the specified index, or null if out of bounds
  • For single values: The value if index is 0, null otherwise
  • For null input: null
  • For invalid index format: null (logs warning)

Examples

final list = ['a', 'b', 'c', 'd'];

// Positive indices
applyIndex(list, '0');   // 'a' (first)
applyIndex(list, '1');   // 'b' (second)
applyIndex(list, '3');   // 'd' (fourth)

// Negative indices
applyIndex(list, '-1');  // 'd' (last)
applyIndex(list, '-2');  // 'c' (second to last)
applyIndex(list, '-4');  // 'a' (fourth from end)

// Out of bounds
applyIndex(list, '10');  // null
applyIndex(list, '-10'); // null

// Single value
applyIndex('value', '0');  // 'value'
applyIndex('value', '1');  // null

// Invalid format
applyIndex(list, 'abc');  // null (logs warning)

Bounds Checking

Indices are checked against list bounds:

  • Positive: Must be < list.length
  • Negative: Must be >= -list.length
  • Out-of-bounds returns null without error

Implementation

dynamic applyIndex(dynamic value, String indexStr) {
  if (value == null) return null;

  // Parse index (handle negative indices)
  final index = int.tryParse(indexStr);
  if (index == null) {
    _log.warning('Invalid index value: $indexStr (must be an integer)');
    return null;
  }

  if (value is List) {
    if (value.isEmpty) return null;

    // Handle negative indices
    final actualIndex = index < 0 ? value.length + index : index;

    // Check bounds
    if (actualIndex < 0 || actualIndex >= value.length) {
      return null;
    }

    return value[actualIndex];
  }

  // For non-list values, index=0 returns the value, others return null
  return index == 0 ? value : null;
}