onSelectedIndexChanged method Null safety

  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.
  //In multiple case we shouldn't to clear the collection as
  // well source properties.
  if (newValue == -1 && canClearSelections()) {
    _clearSelectedRow(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();
  }
}