updateSelected method

void updateSelected(
  1. bool deselectParentWhenChildrenDeselected
)

Updates selected based on the direct childrens' state. selected will not be forced to false if deselectParentWhenChildrenDeselected is false and either there are no children or all children are deselected.

Since this only updates the state based on direct children, you would normally only call this in a depth-first manner on all parents, for example:

item.executeForAllParents((parent) => parent
  ?.updateSelected(widget.deselectParentWhenChildrenDeselected))

Implementation

void updateSelected(bool deselectParentWhenChildrenDeselected) {
  var hasNull = false;
  var hasFalse = false;
  var hasTrue = false;

  for (final child in children) {
    if (child.selected == null) {
      hasNull = true;
    } else if (child.selected == false) {
      hasFalse = true;
    } else if (child.selected == true) {
      hasTrue = true;
    }
  }

  if (!deselectParentWhenChildrenDeselected &&
      (children.isEmpty || (!hasNull && hasFalse && !hasTrue))) {
    if (selected == null && children.isEmpty) {
      // should not be possible unless children were removed after the
      // selected was updated previously...
      selected = true;
    } else if (selected == true) {
      // we're now only in a partially selected state
      selected = null;
    }
  } else {
    selected = hasNull || (hasTrue && hasFalse) ? null : hasTrue;
  }
}