fillSublist method

List<T> fillSublist(
  1. T newValue, [
  2. String sublistName = 'checks'
])

Returns a new list where all elements of the specified sublist are replaced with a given value.

This method iterates through the list and, for each entry containing the specified sublist, replaces all its elements with newValue. By default, it modifies the sublist named 'checks', but a different sublist can be specified using sublistName.

The original list remains unchanged, and a new modified list is returned.

Example:

List<Map<String, dynamic>> tasks = [
  {'name': 'Task 1', 'checks': [true, false, true]},
  {'name': 'Task 2', 'checks': [false, false]}
];

List<Map<String, dynamic>> updatedTasks = tasks.fillSublist(false);

print(updatedTasks);
// Output:
// [
//   {'name': 'Task 1', 'checks': [false, false, false]},
//   {'name': 'Task 2', 'checks': [false, false]}
// ]
  • newValue The value to replace all elements in the sublist.
  • sublistName (optional) The key name of the sublist to modify (default is 'checks').

Returns a new list with the modified sublists.

Implementation

List<T> fillSublist(T newValue, [String sublistName = 'checks']) {
  List<T> parent = this.toList();

  for (dynamic entry in parent) {
    if (entry.containsKey(sublistName) && entry[sublistName] is List<T>) {
      entry[sublistName] = List.filled(entry[sublistName].length, newValue);
    }
  }

  return parent;
}