onSelectedIndexChanged method

  1. @override
void onSelectedIndexChanged()
override

Called when the selectedIndex property in SfDataGrid.controller is changed.

Implementation

@override
void onSelectedIndexChanged() {
  final DataGridConfiguration dataGridConfiguration =
      _dataGridStateDetails!();

  if (dataGridConfiguration.selectionMode == SelectionMode.none) {
    return;
  }

  final int newValue = dataGridConfiguration.controller.selectedIndex;
  if (effectiveRows(dataGridConfiguration.source).isEmpty ||
      newValue > effectiveRows(dataGridConfiguration.source).length) {
    return;
  }

  bool canClearSelections() =>
      _selectedRows.isNotEmpty &&
      dataGridConfiguration.selectionMode != SelectionMode.multiple;

  //If newValue is negative we have to clear the whole selection data.
  if (newValue == -1 && _selectedRows.isNotEmpty) {
    // If selection mode is multiple we need to clear all the selected rows.
    if (dataGridConfiguration.selectionMode == SelectionMode.multiple) {
      _clearSelectedRows(dataGridConfiguration);
    } else {
      _clearSelectedRow(dataGridConfiguration);
    }

    // Issue:
    // FLUT-7123-The current cell is not removed when setting the selected index as -1 through the SelectionController
    // We removed the selected rows only when setting the selected index as -1 from the controller
    // We have resolved the issue by removing the current cell too.
    if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) {
      _clearCurrentCell(dataGridConfiguration);
    }
    notifyListeners();
    return;
  }

  final DataGridRow? record =
      selection_helper.getRecord(dataGridConfiguration, newValue);
  if (record != null && !_selectedRows.contains(record)) {
    //In multiple case we shouldn't to clear the collection as
    // well source properties.
    if (canClearSelections()) {
      _clearSelectedRow(dataGridConfiguration);
    }

    if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) {
      _addCurrentCell(record, dataGridConfiguration,
          isSelectionChanging: true);
    } else {
      final int rowIndex =
          selection_helper.resolveToRowIndex(dataGridConfiguration, record);
      final int columnIndex =
          grid_helper.resolveToStartColumnIndex(dataGridConfiguration);
      dataGridConfiguration.currentCell
          ._updateCurrentRowColumnIndex(rowIndex, columnIndex);
    }

    _addSelection(record, dataGridConfiguration);
    notifyListeners();
  }
}