build method Null safety

  1. @override
Widget? build(
  1. BuildContext context,
  2. int index
)
override

Returns the child with the given index.

Should return null if asked to build a widget with a greater index than exists. If this returns null, estimatedChildCount must subsequently return a precise non-null value (which is then used to implement RenderSliverBoxChildManager.childCount).

Subclasses typically override this function and wrap their children in AutomaticKeepAlive, IndexedSemantics, and RepaintBoundary widgets.

The values returned by this method are cached. To indicate that the widgets have changed, a new delegate must be provided, and the new delegate's shouldRebuild method must return true.

Implementation

@override
@pragma('vm:notify-debugger-on-exception')
Widget? build(BuildContext context, int index) {
  assert(builder != null);
  if (index < 0 || (childCount != null && index >= childCount!))
    return null;
  Widget? child;
  try {
    child = builder(context, index);
  } catch (exception, stackTrace) {
    child = _createErrorWidget(exception, stackTrace);
  }
  if (child == null) {
    return null;
  }
  final Key? key = child.key != null ? _SaltedValueKey(child.key!) : null;
  if (addRepaintBoundaries)
    child = RepaintBoundary(child: child);
  if (addSemanticIndexes) {
    final int? semanticIndex = semanticIndexCallback(child, index);
    if (semanticIndex != null)
      child = IndexedSemantics(index: semanticIndex + semanticIndexOffset, child: child);
  }
  if (addAutomaticKeepAlives)
    child = AutomaticKeepAlive(child: child);
  return KeyedSubtree(key: key, child: child);
}