debugChildrenHaveDuplicateKeys function Null safety

bool debugChildrenHaveDuplicateKeys(
  1. Widget parent,
  2. Iterable<Widget> children

Asserts if the given child list contains any duplicate non-null keys.

To invoke this function, use the following pattern, typically in the relevant Widget's constructor:

assert(!debugChildrenHaveDuplicateKeys(this, children));

For a version of this function that can be used in contexts where the list of items does not have a particular parent, see debugItemsHaveDuplicateKeys.

Does nothing if asserts are disabled. Always returns true.


bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable<Widget> children) {
  assert(() {
    final Key? nonUniqueKey = _firstNonUniqueKey(children);
    if (nonUniqueKey != null) {
      throw FlutterError(
        'Duplicate keys found.\n'
        'If multiple keyed nodes exist as children of another node, they must have unique keys.\n'
        '$parent has multiple children with key $nonUniqueKey.',
    return true;
  return false;