Skip to content

Commit 173bf86

Browse files
authored
Fix CarouselView rebuild (#152791)
Fixes flutter/flutter#152787 Originally, when we want to update `itemExtent`, we didn't check if the old itemExtent is null but `getItemFromPixels()` needs that information. https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/carousel.dart#L1343-L1347 Then in `getItemFromPixels()`, it goes to the else statement which assert `flexWeights` is not null, then the exception happens. - [x ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement].
1 parent 84eb378 commit 173bf86

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

packages/flutter/lib/src/material/carousel.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1340,7 +1340,7 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro
13401340
if (_itemExtent == value) {
13411341
return;
13421342
}
1343-
if (hasPixels) {
1343+
if (hasPixels && _itemExtent != null) {
13441344
final double leadingItem = getItemFromPixels(pixels, viewportDimension);
13451345
final double newPixel = getPixelsFromItem(leadingItem, flexWeights, value);
13461346
forcePixels(newPixel);

packages/flutter/test/material/carousel_test.dart

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1149,6 +1149,50 @@ void main() {
11491149
expect(getItem(5), findsOneWidget);
11501150
expect(tester.getRect(getItem(5)).width, difference);
11511151
});
1152+
1153+
testWidgets('Updating CarouselView does not cause exception', (WidgetTester tester) async {
1154+
// Regression test for https://github.com/flutter/flutter/issues/152787
1155+
bool isLight = true;
1156+
await tester.pumpWidget(
1157+
StatefulBuilder(
1158+
builder: (BuildContext context, StateSetter setState) {
1159+
return MaterialApp(
1160+
theme: Theme.of(context).copyWith(
1161+
brightness: isLight ? Brightness.light : Brightness.dark,
1162+
),
1163+
home: Scaffold(
1164+
appBar: AppBar(
1165+
actions: <Widget>[
1166+
Switch(
1167+
value: isLight,
1168+
onChanged: (bool value) {
1169+
setState(() {
1170+
isLight = value;
1171+
});
1172+
}
1173+
)
1174+
],
1175+
),
1176+
body: CarouselView(
1177+
itemExtent: 100,
1178+
children: List<Widget>.generate(10, (int index) {
1179+
return Center(
1180+
child: Text('Item $index'),
1181+
);
1182+
}),
1183+
),
1184+
),
1185+
);
1186+
}
1187+
)
1188+
);
1189+
await tester.pumpAndSettle();
1190+
await tester.tap(find.byType(Switch));
1191+
await tester.pumpAndSettle();
1192+
1193+
// No exception.
1194+
expect(tester.takeException(), isNull);
1195+
});
11521196
}
11531197

11541198
Finder getItem(int index) {

0 commit comments

Comments
 (0)