debugChildrenHaveDuplicateKeys function

bool debugChildrenHaveDuplicateKeys(
  1. Widget parent,
  2. Iterable<Widget> children,
  3. {String? message}
)

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

To invoke this function, use the following pattern:

class MyWidget extends StatelessWidget {
  MyWidget({ super.key, required this.children }) {
    assert(!debugChildrenHaveDuplicateKeys(this, children));
  }

  final List<Widget> children;

  // ...
}

If specified, the message overrides the default message.

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 false.

Implementation

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