divideListByFunction method

List<List<T>> divideListByFunction(
  1. bool condition(
    1. T
    )
)

Implementation

List<List<T>> divideListByFunction(bool Function(T) condition) {
  List<List<T>> nestedLists = [];
  List<T> currentSublist = [];
  if (isNullOrEmpty) return [];

  for (T element in this ?? []) {
    if (condition(element)) {
      // Start a new sublist when the condition is met.
      if (currentSublist.isNotEmpty) {
        nestedLists.add(List<T>.from(currentSublist));
        currentSublist.clear();
      }
    } else {
      // Add the element to the current sublist.
      currentSublist.add(element);
    }
  }

  // Add the last sublist if it's not empty.
  if (currentSublist.isNotEmpty) {
    nestedLists.add(List<T>.from(currentSublist));
  }

  return nestedLists;
}