Skip to content

Commit e60894b

Browse files
Mairramerflutter-zl
authored andcommitted
Add leadingIndex to CarouselController and onItemChanged to CarouselView (flutter#180667)
Adds a `leadingIndex` property to CarouselController and an `onItemChanged` callback to CarouselView. Closes flutter#169207 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 4ca5f00 commit e60894b

2 files changed

Lines changed: 303 additions & 1 deletion

File tree

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

Lines changed: 100 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ class CarouselView extends StatefulWidget {
145145
this.enableSplash = true,
146146
required double this.itemExtent,
147147
required this.children,
148+
this.onIndexChanged,
148149
}) : consumeMaxWeight = true,
149150
flexWeights = null,
150151
itemBuilder = null,
@@ -209,6 +210,7 @@ class CarouselView extends StatefulWidget {
209210
this.enableSplash = true,
210211
required List<int> this.flexWeights,
211212
required this.children,
213+
this.onIndexChanged,
212214
}) : itemExtent = null,
213215
itemBuilder = null,
214216
itemCount = null;
@@ -252,6 +254,7 @@ class CarouselView extends StatefulWidget {
252254
required double this.itemExtent,
253255
required this.itemBuilder,
254256
this.itemCount,
257+
this.onIndexChanged,
255258
}) : consumeMaxWeight = true,
256259
flexWeights = null,
257260
children = const <Widget>[];
@@ -309,6 +312,7 @@ class CarouselView extends StatefulWidget {
309312
required List<int> this.flexWeights,
310313
required this.itemBuilder,
311314
this.itemCount,
315+
this.onIndexChanged,
312316
}) : itemExtent = null,
313317
children = const <Widget>[];
314318

@@ -448,6 +452,34 @@ class CarouselView extends StatefulWidget {
448452
/// The child widgets for the carousel.
449453
final List<Widget> children;
450454

455+
/// {@template flutter.material.CarouselView.onIndexChanged}
456+
/// A callback invoked when the leading item changes.
457+
///
458+
/// The leading item is the first visible item in the carousel view.
459+
///
460+
/// The callback fires only when the leading item is completely out of view,
461+
/// whether due to user interaction or programmatic scrolling. If the leading item
462+
/// remains partially visible, the leading index will not change and the callback will
463+
/// not be invoked.
464+
/// {@endtemplate}
465+
///
466+
/// Example:
467+
///
468+
/// ```dart
469+
/// CarouselView(
470+
/// itemExtent: 200.0,
471+
/// onIndexChanged: (int index) {
472+
/// print('Leading item changed to: $index');
473+
/// },
474+
/// children: <Widget>[
475+
/// Container(color: Colors.red),
476+
/// Container(color: Colors.green),
477+
/// Container(color: Colors.blue),
478+
/// ],
479+
/// )
480+
/// ```
481+
final ValueChanged<int>? onIndexChanged;
482+
451483
/// Called to build carousel item on demand.
452484
///
453485
/// Will be called only for indices greater than or equal to zero and less
@@ -472,6 +504,7 @@ class _CarouselViewState extends State<CarouselView> {
472504
bool get _consumeMaxWeight => widget.consumeMaxWeight;
473505
CarouselController? _internalController;
474506
CarouselController get _controller => widget.controller ?? _internalController!;
507+
late int _lastReportedLeadingItem;
475508

476509
@override
477510
void initState() {
@@ -480,7 +513,9 @@ class _CarouselViewState extends State<CarouselView> {
480513
if (widget.controller == null) {
481514
_internalController = CarouselController();
482515
}
516+
_lastReportedLeadingItem = _getInitialLeadingItem();
483517
_controller._attach(this);
518+
_controller.addListener(_handleScroll);
484519
}
485520

486521
@override
@@ -513,11 +548,39 @@ class _CarouselViewState extends State<CarouselView> {
513548

514549
@override
515550
void dispose() {
551+
_controller.removeListener(_handleScroll);
516552
_controller._detach(this);
517553
_internalController?.dispose();
518554
super.dispose();
519555
}
520556

557+
void _handleScroll() {
558+
if (widget.onIndexChanged == null) {
559+
return;
560+
}
561+
562+
final ScrollPosition position = _controller.position;
563+
final int currentLeadingIndex = (position as _CarouselPosition).leadingItem;
564+
565+
if (currentLeadingIndex != _lastReportedLeadingItem) {
566+
_lastReportedLeadingItem = currentLeadingIndex;
567+
widget.onIndexChanged!(currentLeadingIndex);
568+
}
569+
}
570+
571+
// For weighted carousel, the initialItem means the index of the item to occupy the first maximum weight
572+
// in flexWeights. To get the initial leading item, it should be initialItem - index of the first max weight in flexWeights.
573+
// So it might be negative when initialItem value is small but the first max weight index is large. In that case,
574+
// the initial leading item should be 0.
575+
int _getInitialLeadingItem() {
576+
if (widget.flexWeights != null) {
577+
final int maxWeight = widget.flexWeights!.max;
578+
final int firstMaxWeightIndex = widget.flexWeights!.indexOf(maxWeight);
579+
return math.max(_controller.initialItem - firstMaxWeightIndex, 0);
580+
}
581+
return _controller.initialItem;
582+
}
583+
521584
AxisDirection _getDirection(BuildContext context) {
522585
switch (widget.scrollDirection) {
523586
case Axis.horizontal:
@@ -636,7 +699,6 @@ class _CarouselViewState extends State<CarouselView> {
636699
_itemExtent = widget.itemExtent == null
637700
? null
638701
: clampDouble(widget.itemExtent!, 0, mainAxisExtent);
639-
640702
return Scrollable(
641703
axisDirection: axisDirection,
642704
controller: _controller,
@@ -1567,6 +1629,27 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro
15671629
_flexWeights = value;
15681630
}
15691631

1632+
// The index of the leading item in the carousel.
1633+
// `getItemFromPixels` may return a fractional value (e.g., 0.6 when mid-scroll).
1634+
// Use `toInt()` to truncate the fractional part, ensuring the leading item
1635+
// only advances after fully crossing the next item's boundary.
1636+
int get leadingItem {
1637+
final int leadingItem = getItemFromPixels(pixels, viewportDimension).toInt();
1638+
// When `consumeMaxWeight` is true, there is some reserved space before
1639+
// item 0 so that item 0 can be expanded to occupy the maximum
1640+
// weight while scrolling. The way how consumeMaxWeight works is that we assume
1641+
// there are some "invisible" items before the first visible item. Therefore,
1642+
// to calculate the correct visible leading item, we need to offset the leading
1643+
// item by the index of the maximum weight.
1644+
//
1645+
// The subtraction may cause negative number for leading item. In this case,
1646+
// constrain the leading item to 0.
1647+
if (consumeMaxWeight && flexWeights != null) {
1648+
return math.max(leadingItem - flexWeights!.indexOf(flexWeights!.max), 0);
1649+
}
1650+
return leadingItem;
1651+
}
1652+
15701653
double updateLeadingItem(List<int>? newFlexWeights, bool newConsumeMaxWeight) {
15711654
final double maxItem;
15721655
if (hasPixels && flexWeights != null) {
@@ -1704,6 +1787,22 @@ class CarouselController extends ScrollController {
17041787
/// The item that expands to the maximum size when first creating the [CarouselView].
17051788
final int initialItem;
17061789

1790+
/// The current leading item index in the [CarouselView].
1791+
///
1792+
/// {@macro flutter.material.CarouselView.onIndexChanged}
1793+
int get leadingItem {
1794+
assert(
1795+
positions.isNotEmpty,
1796+
'CarouselController.leadingItem cannot be accessed before a CarouselView is built with it.',
1797+
);
1798+
assert(
1799+
positions.length == 1,
1800+
'CarouselController.leadingItem cannot be read when multiple CarouselViews '
1801+
'are attached to the same controller.',
1802+
);
1803+
return (position as _CarouselPosition).leadingItem;
1804+
}
1805+
17071806
_CarouselViewState? _carouselState;
17081807

17091808
// ignore: use_setters_to_change_properties

‎packages/flutter/test/material/carousel_test.dart‎

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1977,6 +1977,209 @@ void main() {
19771977
});
19781978
});
19791979

1980+
group('CarouselView onIndexChanged callback', () {
1981+
Widget buildCarousel({
1982+
required CarouselController controller,
1983+
ValueChanged<int>? onIndexChanged,
1984+
bool weighted = false,
1985+
bool reverse = false,
1986+
bool itemSnapping = false,
1987+
List<int>? flexWeights,
1988+
int itemCount = 6,
1989+
}) {
1990+
return MaterialApp(
1991+
home: Scaffold(
1992+
body: weighted
1993+
? CarouselView.weighted(
1994+
flexWeights: flexWeights!,
1995+
reverse: reverse,
1996+
itemSnapping: itemSnapping,
1997+
controller: controller,
1998+
onIndexChanged: onIndexChanged,
1999+
children: List.generate(itemCount, (i) => Text('Item $i')),
2000+
)
2001+
: CarouselView(
2002+
itemExtent: 300,
2003+
reverse: reverse,
2004+
itemSnapping: itemSnapping,
2005+
controller: controller,
2006+
onIndexChanged: onIndexChanged,
2007+
children: List.generate(itemCount, (i) => Text('Item $i')),
2008+
),
2009+
),
2010+
);
2011+
}
2012+
2013+
testWidgets('CarouselView shows correct item after animation', (tester) async {
2014+
final controller = CarouselController();
2015+
addTearDown(controller.dispose);
2016+
var leadingIndex = 0;
2017+
2018+
await tester.pumpWidget(
2019+
buildCarousel(controller: controller, onIndexChanged: (i) => leadingIndex = i),
2020+
);
2021+
await tester.pumpAndSettle();
2022+
2023+
controller.animateToItem(
2024+
3,
2025+
duration: const Duration(milliseconds: 200),
2026+
curve: Curves.linear,
2027+
);
2028+
await tester.pumpAndSettle();
2029+
2030+
expect(controller.leadingItem, equals(3));
2031+
expect(leadingIndex, equals(3));
2032+
2033+
controller.animateToItem(
2034+
1,
2035+
duration: const Duration(milliseconds: 200),
2036+
curve: Curves.linear,
2037+
);
2038+
await tester.pumpAndSettle();
2039+
expect(controller.leadingItem, equals(1));
2040+
expect(leadingIndex, equals(1));
2041+
});
2042+
2043+
testWidgets(
2044+
'CarouselView.weighted shows correct item after animation with symmetric flexWeights',
2045+
(tester) async {
2046+
final controller = CarouselController();
2047+
addTearDown(controller.dispose);
2048+
var leadingIndex = 0;
2049+
2050+
await tester.pumpWidget(
2051+
buildCarousel(
2052+
weighted: true,
2053+
flexWeights: const [2, 5, 2],
2054+
controller: controller,
2055+
onIndexChanged: (i) => leadingIndex = i,
2056+
),
2057+
);
2058+
await tester.pumpAndSettle();
2059+
2060+
// Animate the carousel so item 4 is placed in the first position with max weight (5)
2061+
// in `flexWeights`, resulting in item 3 as the leading item.
2062+
controller.animateToItem(
2063+
4,
2064+
duration: const Duration(milliseconds: 200),
2065+
curve: Curves.linear,
2066+
);
2067+
await tester.pumpAndSettle();
2068+
2069+
expect(controller.leadingItem, equals(3));
2070+
expect(leadingIndex, equals(3));
2071+
expect(find.text('Item 3'), findsOneWidget);
2072+
},
2073+
);
2074+
2075+
testWidgets(
2076+
'CarouselView.weighted shows correct item after animation with asymmetric flexWeights',
2077+
(tester) async {
2078+
final controller = CarouselController();
2079+
addTearDown(controller.dispose);
2080+
var leadingIndex = 0;
2081+
2082+
await tester.pumpWidget(
2083+
buildCarousel(
2084+
weighted: true,
2085+
flexWeights: const [1, 2, 3, 4],
2086+
controller: controller,
2087+
onIndexChanged: (i) => leadingIndex = i,
2088+
),
2089+
);
2090+
await tester.pumpAndSettle();
2091+
2092+
controller.animateToItem(
2093+
2,
2094+
duration: const Duration(milliseconds: 200),
2095+
curve: Curves.linear,
2096+
);
2097+
await tester.pumpAndSettle();
2098+
2099+
expect(controller.leadingItem, equals(0));
2100+
expect(leadingIndex, equals(0));
2101+
},
2102+
);
2103+
2104+
testWidgets('CarouselView shows the correct item after dragging', (tester) async {
2105+
final controller = CarouselController();
2106+
addTearDown(controller.dispose);
2107+
var leadingIndex = 0;
2108+
2109+
await tester.pumpWidget(
2110+
buildCarousel(
2111+
weighted: true,
2112+
flexWeights: const [2, 5, 2],
2113+
itemSnapping: true,
2114+
itemCount: 5,
2115+
controller: controller,
2116+
onIndexChanged: (i) => leadingIndex = i,
2117+
),
2118+
);
2119+
await tester.pumpAndSettle();
2120+
2121+
await tester.drag(find.byType(CarouselView), const Offset(-300, 0));
2122+
await tester.pumpAndSettle();
2123+
2124+
expect(controller.leadingItem, equals(1));
2125+
expect(leadingIndex, equals(1));
2126+
});
2127+
2128+
testWidgets('CarouselView with reverse=true reports correct leading item after animation', (
2129+
tester,
2130+
) async {
2131+
final controller = CarouselController();
2132+
addTearDown(controller.dispose);
2133+
var leadingIndex = 0;
2134+
2135+
await tester.pumpWidget(
2136+
buildCarousel(
2137+
reverse: true,
2138+
controller: controller,
2139+
onIndexChanged: (i) => leadingIndex = i,
2140+
),
2141+
);
2142+
await tester.pumpAndSettle();
2143+
2144+
controller.animateToItem(
2145+
2,
2146+
duration: const Duration(milliseconds: 200),
2147+
curve: Curves.linear,
2148+
);
2149+
await tester.pumpAndSettle();
2150+
2151+
expect(controller.leadingItem, equals(2));
2152+
expect(leadingIndex, equals(2));
2153+
});
2154+
2155+
testWidgets('CarouselView.weighted with reverse=true reports correct leading item after drag', (
2156+
tester,
2157+
) async {
2158+
final controller = CarouselController();
2159+
addTearDown(controller.dispose);
2160+
var leadingIndex = 0;
2161+
2162+
await tester.pumpWidget(
2163+
buildCarousel(
2164+
weighted: true,
2165+
reverse: true,
2166+
itemSnapping: true,
2167+
itemCount: 5,
2168+
flexWeights: const [2, 5, 2],
2169+
controller: controller,
2170+
onIndexChanged: (i) => leadingIndex = i,
2171+
),
2172+
);
2173+
await tester.pumpAndSettle();
2174+
2175+
await tester.drag(find.byType(CarouselView), const Offset(300, 0));
2176+
await tester.pumpAndSettle();
2177+
2178+
expect(controller.leadingItem, equals(1));
2179+
expect(leadingIndex, equals(1));
2180+
});
2181+
});
2182+
19802183
group('CarouselView item clipBehavior', () {
19812184
testWidgets('CarouselView Item clipBehavior defaults to Clip.antiAlias', (
19822185
WidgetTester tester,

0 commit comments

Comments
 (0)