Skip to content

Fix Carousel crashes when using PageStorageKey #166817

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/material/carousel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,7 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro
// If resize from zero, we should use the _cachedItem to recover the state.
item = _cachedItem!;
} else {
item = getItemFromPixels(oldPixels, oldViewportDimensions!);
item = getItemFromPixels(oldPixels, oldViewportDimensions ?? viewportDimension);
}
final double newPixels = getPixelsFromItem(item, flexWeights, itemExtent);
// If the viewportDimension is zero, cache the item
Expand Down
41 changes: 41 additions & 0 deletions packages/flutter/test/material/carousel_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1433,6 +1433,47 @@ void main() {
expect(tester.takeException(), isNull);
});

// Regression test for https://github.com/flutter/flutter/issues/166067.
testWidgets('CarouselView should not crash when using PageStorageKey', (
WidgetTester tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return const <Widget>[SliverAppBar()];
},
body: CustomScrollView(
key: const PageStorageKey<String>('key1'),
slivers: <Widget>[
SliverToBoxAdapter(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 50),
child: CarouselView.weighted(
flexWeights: const <int>[1, 2],
consumeMaxWeight: false,
children: List<Widget>.generate(20, (int index) {
return ColoredBox(
color: Colors.primaries[index % Colors.primaries.length].withValues(
alpha: 0.8,
),
child: const SizedBox.expand(),
);
}),
),
),
),
],
),
),
),
),
);

expect(tester.takeException(), isNull);
});

group('CarouselController.animateToItem', () {
testWidgets('CarouselView.weighted horizontal, not reversed, flexWeights [7,1]', (
WidgetTester tester,
Expand Down