diff --git a/packages/flutter/lib/src/material/carousel.dart b/packages/flutter/lib/src/material/carousel.dart index 59900eb9ff9..71957e79af4 100644 --- a/packages/flutter/lib/src/material/carousel.dart +++ b/packages/flutter/lib/src/material/carousel.dart @@ -579,6 +579,10 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor // This implements the [itemExtentBuilder] callback. double _buildItemExtent(int index, SliverLayoutDimensions currentLayoutDimensions) { + if (maxExtent == 0.0) { + return maxExtent; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); // Calculate how many items have been completely scroll off screen. @@ -641,6 +645,10 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor double itemExtent, int index, ) { + if (maxExtent == 0.0) { + return maxExtent; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); // If there is not enough space to place the last visible item but the remaining @@ -673,6 +681,10 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor ) double itemExtent, ) { + if (maxExtent == 0.0) { + return 0; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); return math.max(firstVisibleIndex, 0); } diff --git a/packages/flutter/test/material/carousel_test.dart b/packages/flutter/test/material/carousel_test.dart index 9784d767a76..dd0a9bac55a 100644 --- a/packages/flutter/test/material/carousel_test.dart +++ b/packages/flutter/test/material/carousel_test.dart @@ -1413,6 +1413,25 @@ void main() { expect(buttonPressed, isTrue); }, ); + + // Regression test for https://github.com/flutter/flutter/issues/160679 + testWidgets('CarouselView does not crash if itemExtent is zero', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 100, + child: CarouselView( + itemExtent: 0, + children: [Container(color: Colors.red, width: 100, height: 100)], + ), + ), + ), + ), + ); + + expect(tester.takeException(), isNull); + }); } Finder getItem(int index) {