insertRowByKey method

Future<bool> insertRowByKey(
  1. Object key,
  2. Map<String, dynamic> map, {
  3. int fromColumn = 2,
  4. dynamic mapTo,
  5. bool appendMissing = false,
  6. bool overwrite = false,
  7. bool eager = true,
})

Updates row values with values from map by column names.

Expands current sheet's size if inserting range is out of sheet's bounds.

The column A considered to be row names

map - map containing values to insert (not null nor empty)

key - name of a requested row (values of returned map)

fromColumn - optional (defaults to 2), column index for the first inserted value, columns start at index 1 (column A)

mapTo - optional, name of a column to which keys of the map will be mapped to, if mapTo is null then values will be mapped to column A

appendMissing - whether keys of map (with its related values) that are not present in a mapTo should be inserted into key row

overwrite - whether clear cells of key row if map does not contain value for them

eager - optional (defaults to true), whether to add key if absent

Returns Future true in case of success.

Throws GSheetsException.

Implementation

Future<bool> insertRowByKey(
  Object key,
  Map<String, dynamic> map, {
  int fromColumn = 2,
  dynamic mapTo,
  bool appendMissing = false,
  bool overwrite = false,
  bool eager = true,
}) async {
  final rKey = parseKey(key);
  final mKey = parseStringOrNull(mapTo);
  checkIndex('fromColumn', fromColumn);
  checkMapTo(rKey, mKey);
  checkMap(map);
  final rows = await _values.allRows();
  final mapToIndex = mKey.isNullOrEmpty ? 0 : whereFirst(rows, mKey!);
  if (mapToIndex < 0) return false;
  var rowIndex = whereFirst(rows, rKey);
  if (rowIndex < 0) {
    if (!eager || rows.isEmpty || rows.first.isEmpty) return false;
    rowIndex = rows.length;
    await _values._ws._update(
      values: [rKey],
      range: await _values._ws._columnRange(1, rowIndex + 1, 1),
      majorDimension: dimenColumns,
    );
  } else {
    checkMapTo(rowIndex + 1, mapToIndex + 1);
  }
  final keys = get(rows, at: mapToIndex, or: <String>[])!;
  return _insertRows(
    rowIndex + 1,
    [map],
    keys,
    fromColumn,
    mapToIndex + 1,
    appendMissing,
    overwrite,
  );
}