childCount property Null safety
override
Called to obtain a precise measure of the total number of children.
Must return the number that is one greater than the greatest index
for
which createChild
will actually create a child.
This is used when createChild cannot add a child for a positive index
,
to determine the precise dimensions of the sliver. It must return an
accurate and precise non-null value. It will not be called if
createChild is always able to create a child (e.g. for an infinite
list).
Implementation
@override
int get childCount {
int? result = estimatedChildCount;
if (result == null) {
// Since childCount was called, we know that we reached the end of
// the list (as in, _build return null once), so we know that the
// list is finite.
// Let's do an open-ended binary search to find the end of the list
// manually.
int lo = 0;
int hi = 1;
final SliverMultiBoxAdaptorWidget adaptorWidget = widget as SliverMultiBoxAdaptorWidget;
const int max = kIsWeb
? 9007199254740992 // max safe integer on JS (from 0 to this number x != x+1)
: ((1 << 63) - 1);
while (_build(hi - 1, adaptorWidget) != null) {
lo = hi - 1;
if (hi < max ~/ 2) {
hi *= 2;
} else if (hi < max) {
hi = max;
} else {
throw FlutterError(
'Could not find the number of children in ${adaptorWidget.delegate}.\n'
"The childCount getter was called (implying that the delegate's builder returned null "
'for a positive index), but even building the child with index $hi (the maximum '
'possible integer) did not return null. Consider implementing childCount to avoid '
'the cost of searching for the final child.',
);
}
}
while (hi - lo > 1) {
final int mid = (hi - lo) ~/ 2 + lo;
if (_build(mid - 1, adaptorWidget) == null) {
hi = mid;
} else {
lo = mid;
}
}
result = lo;
}
return result;
}