diff --git a/packages/flutter/lib/src/material/carousel.dart b/packages/flutter/lib/src/material/carousel.dart index a57d819375..19c85a7e3b 100644 --- a/packages/flutter/lib/src/material/carousel.dart +++ b/packages/flutter/lib/src/material/carousel.dart @@ -1340,7 +1340,7 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro if (_itemExtent == value) { return; } - if (hasPixels) { + if (hasPixels && _itemExtent != null) { final double leadingItem = getItemFromPixels(pixels, viewportDimension); final double newPixel = getPixelsFromItem(leadingItem, flexWeights, value); forcePixels(newPixel); diff --git a/packages/flutter/test/material/carousel_test.dart b/packages/flutter/test/material/carousel_test.dart index 3754711935..062e41d02a 100644 --- a/packages/flutter/test/material/carousel_test.dart +++ b/packages/flutter/test/material/carousel_test.dart @@ -1149,6 +1149,50 @@ void main() { expect(getItem(5), findsOneWidget); expect(tester.getRect(getItem(5)).width, difference); }); + + testWidgets('Updating CarouselView does not cause exception', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/152787 + bool isLight = true; + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return MaterialApp( + theme: Theme.of(context).copyWith( + brightness: isLight ? Brightness.light : Brightness.dark, + ), + home: Scaffold( + appBar: AppBar( + actions: [ + Switch( + value: isLight, + onChanged: (bool value) { + setState(() { + isLight = value; + }); + } + ) + ], + ), + body: CarouselView( + itemExtent: 100, + children: List.generate(10, (int index) { + return Center( + child: Text('Item $index'), + ); + }), + ), + ), + ); + } + ) + ); + await tester.pumpAndSettle(); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + + // No exception. + expect(tester.takeException(), isNull); + }); } Finder getItem(int index) {