### Basic CarouselSlider Usage in Flutter Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider Demonstrates the basic implementation of a CarouselSlider widget. It requires a list of items and CarouselOptions for configuration. The example uses a simple list of numbers and returns a Container for each item. ```dart CarouselSlider( options: CarouselOptions(height: 400.0), items: [1,2,3,4,5].map((i) { return Builder( builder: (BuildContext context) { return Container( width: MediaQuery.of(context).size.width, margin: EdgeInsets.symmetric(horizontal: 5.0), decoration: BoxDecoration( color: Colors.amber ), child: Text('text $i', style: TextStyle(fontSize: 16.0),) ); }, ); }).toList(), ) ``` -------------------------------- ### Example createState Implementation in Dart Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider/createState This snippet demonstrates the standard implementation of the createState method for a widget in Dart. It returns a new instance of the associated State subclass. This method is crucial for managing the mutable state of a StatefulWidget. ```dart @override State createState() => _SomeWidgetState(); ``` -------------------------------- ### Flutter State Example: Correct Closure Capture in Build Method Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/build Demonstrates how closures created within the `build` method of a `State` object correctly capture the widget's state across rebuilds. This is crucial for preventing bugs where closures might hold references to outdated widget instances. ```dart class MyButton extends StatefulWidget { const MyButton({super.key, this.color = Colors.teal}); final Color color; // ... } class MyButtonState extends State { // ... @override Widget build(BuildContext context) { return SpecialWidget( handler: () { print('color: ${widget.color}'); }, ); } } ``` -------------------------------- ### Flutter Incorrect Closure Capture Example (Conceptual) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/build Illustrates a conceptual (non-valid Flutter code) example of how closures might incorrectly capture the widget instance if the build method were part of `StatefulWidget`, leading to outdated state references. ```dart // (this is not valid Flutter code) class MyButton extends StatefulWidgetX { MyButton({super.key, required this.color}); final Color color; @override Widget build(BuildContext context, State state) { return SpecialWidget( handler: () { print('color: $color'); }, ); } } ``` -------------------------------- ### Dart initState Method Implementation for Carousel Slider Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/initState The initState method is called exactly once when the State object is inserted into the widget tree. It's used for initialization that depends on the widget's configuration and context. This implementation sets up the CarouselState, configures the PageController with specified options, and initiates auto-play if enabled. It ensures proper setup of carousel properties like itemCount, initialPage, and realPage. ```dart @override void initState() { super.initState(); carouselState = CarouselState(this.options, clearTimer, resumeTimer, this.changeMode); carouselState!.itemCount = widget.itemCount; carouselController.state = carouselState; carouselState!.initialPage = widget.options.initialPage; carouselState!.realPage = options.enableInfiniteScroll ? carouselState!.realPage + carouselState!.initialPage : carouselState!.initialPage; handleAutoPlay(); pageController = PageController( viewportFraction: options.viewportFraction, initialPage: carouselState!.realPage, ); carouselState!.pageController = pageController; } ``` -------------------------------- ### Flutter Widget Lifecycle: Implementing the dispose Method Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/dispose This example demonstrates the standard implementation of the dispose method within a Flutter State object. It ensures proper cleanup by calling the inherited dispose method and then releasing custom resources, such as timers. ```dart @override void dispose() { super.dispose(); clearTimer(); } ``` -------------------------------- ### CarouselOptions Constructor and Properties Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselOptions-class This section details the constructor for the CarouselOptions class and lists all its configurable properties, along with their types and descriptions. ```APIDOC ## CarouselOptions Class ### Description The `CarouselOptions` class is used to configure the behavior and appearance of a carousel slider. ### Constructor `CarouselOptions.new(` `double? height,` `double aspectRatio = 16 / 9,` `double viewportFraction = 0.8,` `int initialPage = 0,` `bool enableInfiniteScroll = true,` `bool animateToClosest = true,` `bool reverse = false,` `bool autoPlay = false,` `Duration autoPlayInterval = const Duration(seconds: 4),` `Duration autoPlayAnimationDuration = const Duration(milliseconds: 800),` `Curve autoPlayCurve = Curves.fastOutSlowIn,` `bool? enlargeCenterPage = false,` `dynamic onPageChanged(int index, CarouselPageChangedReason reason)?,` `ValueChanged? onScrolled,` `ScrollPhysics? scrollPhysics,` `bool pageSnapping = true,` `Axis scrollDirection = Axis.horizontal,` `bool pauseAutoPlayOnTouch = true,` `bool pauseAutoPlayOnManualNavigate = true,` `bool pauseAutoPlayInFiniteScroll = false,` `PageStorageKey? pageViewKey,` `CenterPageEnlargeStrategy enlargeStrategy = CenterPageEnlargeStrategy.scale,` `double enlargeFactor = 0.3,` `bool disableCenter = false,` `bool padEnds = true,` `Clip clipBehavior = Clip.hardEdge` `) ### Properties - **animateToClosest** (bool) - Determines if carousel should loop to the closest occurence of requested page. `final` - **aspectRatio** (double) - Aspect ratio is used if no height have been declared. `final` - **autoPlay** (bool) - Enables auto play, sliding one page at a time. `final` - **autoPlayAnimationDuration** (Duration) - The animation duration between two transitioning pages while in auto playback. `final` - **autoPlayCurve** (Curve) - Determines the animation curve physics. `final` - **autoPlayInterval** (Duration) - Sets Duration to determent the frequency of slides when. `final` - **clipBehavior** (Clip) - Exposed clipBehavior of PageView. `final` - **disableCenter** (bool) - Whether or not to disable the `Center` widget for each slide. `final` - **enableInfiniteScroll** (bool) - Determines if carousel should loop infinitely or be limited to item length. `final` - **enlargeCenterPage** (bool?) - Determines if current page should be larger than the side images, creating a feeling of depth in the carousel. `final` - **enlargeFactor** (double) - How much the pages next to the center page will be scaled down. If `enlargeCenterPage` is false, this property has no effect. `final` - **enlargeStrategy** (CenterPageEnlargeStrategy) - Use enlargeStrategy to determine which method to enlarge the center page. `final` - **hashCode** (int) - The hash code for this object. `no setter inherited` - **height** (double?) - Set carousel height and overrides any existing aspectRatio. `final` - **initialPage** (int) - The initial page to show when first creating the CarouselSlider. `final` - **onPageChanged** (dynamic Function(int index, CarouselPageChangedReason reason)?) - Called whenever the page in the center of the viewport changes. `final` - **onScrolled** (ValueChanged?) - Called whenever the carousel is scrolled. `final` - **padEnds** (bool) - Whether to add padding to both ends of the list. If this is set to true and viewportFraction < 1.0, padding will be added such that the first and last child slivers will be in the center of the viewport when scrolled all the way to the start or end, respectively. If viewportFraction >= 1.0, this property has no effect. This property defaults to true and must not be null. `final` - **pageSnapping** (bool) - Set to false to disable page snapping, useful for custom scroll behavior. `final` - **pageViewKey** (PageStorageKey?) - Pass a `PageStoragekey` if you want to keep the pageview's position when it was recreated. `final` - **pauseAutoPlayInFiniteScroll** (bool) - If `enableInfiniteScroll` is `false`, and `autoPlay` is `true`, this option decide the carousel should go to the first item when it reach the last item or not. If set to `true`, the auto play will be paused when it reach the last item. If set to `false`, the auto play function will animate to the first item when it was in the last item. `final` - **pauseAutoPlayOnManualNavigate** (bool) - If `true`, the auto play function will be paused when user is calling pageController's `nextPage` or `previousPage` or `animateToPage` method. And after the animation complete, the auto play will be resumed. Default to `true`. `final` - **pauseAutoPlayOnTouch** (bool) - If `true`, the auto play function will be paused when user is interacting with the carousel, and will be resumed when user finish interacting. Default to `true`. `final` - **reverse** (bool) - Reverse the order of items if set to true. `final` - **runtimeType** (Type) - A representation of the runtime type of the object. `no setter inherited` - **scrollDirection** (Axis) - The axis along which the page view scrolls. `final` - **scrollPhysics** (ScrollPhysics?) - How the carousel should respond to user input. `final` - **viewportFraction** (double) - The fraction of the viewport that each page should occupy. `final` ``` -------------------------------- ### CarouselOptions Constructor Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselOptions/CarouselOptions This section details the parameters available for the CarouselOptions constructor, allowing for extensive customization of the carousel slider's features. ```APIDOC ## CarouselOptions Constructor ### Description Initializes a new instance of the CarouselOptions class with specified configuration for a carousel slider. ### Method Constructor ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart CarouselOptions( height: 200.0, autoPlay: true, aspectRatio: 16 / 9, viewportFraction: 0.8, initialPage: 0, enableInfiniteScroll: true, animateToClosest: true, reverse: false, autoPlayInterval: Duration(seconds: 3), autoPlayAnimationDuration: Duration(milliseconds: 500), autoPlayCurve: Curves.easeInOut, enlargeCenterPage: true, onPageChanged: (index, reason) => print('Page changed to: $index'), onScrolled: (double? offset) => print('Scrolled by: $offset'), scrollPhysics: AlwaysScrollableScrollPhysics(), pageSnapping: true, scrollDirection: Axis.horizontal, pauseAutoPlayOnTouch: true, pauseAutoPlayOnManualNavigate: true, pauseAutoPlayInFiniteScroll: false, pageViewKey: PageStorageKey('carouselSlider'), enlargeStrategy: CenterPageEnlargeStrategy.scale, enlargeFactor: 0.4, disableCenter: false, padEnds: true, clipBehavior: Clip.antiAlias, ) ``` ### Response #### Success Response (200) This is a constructor, it does not return a response in the traditional API sense. It creates an instance of CarouselOptions. #### Response Example N/A (Constructor) ``` -------------------------------- ### CarouselSlider Constructors Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider-class Demonstrates the two primary constructors for the CarouselSlider class: 'new' for providing a list of widgets and 'builder' for an on-demand item builder. Both require a list of widgets or an item count, and CarouselOptions for configuration. ```dart CarouselSlider.new({ required List? items, required CarouselOptions options, bool? disableGesture, CarouselSliderController? carouselController, Key? key }) CarouselSlider.builder({ required int? itemCount, required ExtendedIndexedWidgetBuilder? itemBuilder, required CarouselOptions options, bool? disableGesture, CarouselSliderController? carouselController, Key? key }) ``` -------------------------------- ### CarouselState Constructor Source: https://pub.dev/documentation/carousel_slider/latest/carousel_state/CarouselState-class The constructor for the CarouselState class initializes the carousel with specified options and callback functions for timer management and mode changes. It requires CarouselOptions, functions to reset and resume the timer, and a function to handle mode changes based on page transition reasons. ```dart CarouselState.new(CarouselOptions options, Function onResetTimer, Function onResumeTimer, dynamic changeMode(CarouselPageChangedReason)) ``` -------------------------------- ### CarouselSlider Configuration Options Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider Illustrates various configuration options available for CarouselSlider through the CarouselOptions class. This includes settings for height, aspect ratio, viewport fraction, auto-play, scrolling direction, and page change callbacks. ```dart CarouselSlider( items: items, options: CarouselOptions( height: 400, aspectRatio: 16/9, viewportFraction: 0.8, initialPage: 0, enableInfiniteScroll: true, reverse: false, autoPlay: true, autoPlayInterval: Duration(seconds: 3), autoPlayAnimationDuration: Duration(milliseconds: 800), autoPlayCurve: Curves.fastOutSlowIn, enlargeCenterPage: true, enlargeFactor: 0.3, onPageChanged: callbackFunction, scrollDirection: Axis.horizontal, ) ) ``` -------------------------------- ### CarouselOptions Constructor and Properties Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselOptions-class This snippet demonstrates the constructor for the CarouselOptions class and outlines its various properties. These properties control functionalities such as animation, auto-play, infinite scroll, page scaling, and scroll direction. It's essential for defining the behavior of a carousel slider. ```dart CarouselOptions({ double? height, double aspectRatio = 16 / 9, double viewportFraction = 0.8, int initialPage = 0, bool enableInfiniteScroll = true, bool animateToClosest = true, bool reverse = false, bool autoPlay = false, Duration autoPlayInterval = const Duration(seconds: 4), Duration autoPlayAnimationDuration = const Duration(milliseconds: 800), Curve autoPlayCurve = Curves.fastOutSlowIn, bool? enlargeCenterPage = false, dynamic onPageChanged(int index, CarouselPageChangedReason reason)?, ValueChanged? onScrolled, ScrollPhysics? scrollPhysics, bool pageSnapping = true, Axis scrollDirection = Axis.horizontal, bool pauseAutoPlayOnTouch = true, bool pauseAutoPlayOnManualNavigate = true, bool pauseAutoPlayInFiniteScroll = false, PageStorageKey? pageViewKey, CenterPageEnlargeStrategy enlargeStrategy = CenterPageEnlargeStrategy.scale, double enlargeFactor = 0.3, bool disableCenter = false, bool padEnds = true, Clip clipBehavior = Clip.hardEdge, }) // Properties: // animateToClosest: bool // aspectRatio: double // autoPlay: bool // autoPlayAnimationDuration: Duration // autoPlayCurve: Curve // autoPlayInterval: Duration // clipBehavior: Clip // disableCenter: bool // enableInfiniteScroll: bool // enlargeCenterPage: bool? // enlargeFactor: double // enlargeStrategy: CenterPageEnlargeStrategy // height: double? // initialPage: int // onPageChanged: dynamic Function(int index, CarouselPageChangedReason reason)? // onScrolled: ValueChanged? // padEnds: bool // pageSnapping: bool // pageViewKey: PageStorageKey? // pauseAutoPlayInFiniteScroll: bool // pauseAutoPlayOnManualNavigate: bool // pauseAutoPlayOnTouch: bool // reverse: bool // scrollDirection: Axis // scrollPhysics: ScrollPhysics? // viewportFraction: double ``` -------------------------------- ### CarouselSliderControllerImpl Methods Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderControllerImpl-class This snippet outlines the core methods of the CarouselSliderControllerImpl class used for controlling a carousel slider. These include animating to pages, jumping between pages, and managing autoplay. ```dart CarouselSliderControllerImpl.new() animateToPage(int page, {Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear}) → Future jumpToPage(int page) → void nextPage({Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear}) → Future previousPage({Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear}) → Future startAutoPlay() → void stopAutoPlay() → void ``` -------------------------------- ### CarouselSlider.builder Constructor (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider/CarouselSlider The CarouselSlider.builder constructor is used to create a CarouselSlider with an on-demand item builder. It requires itemCount, itemBuilder, and options, and supports optional disableGesture and carouselController. The implementation initializes internal properties and assigns a controller. ```dart CarouselSlider.builder({ required int? itemCount, required ExtendedIndexedWidgetBuilder? itemBuilder, required CarouselOptions options, bool? disableGesture, CarouselSliderController? carouselController, Key? key, }) // Implementation CarouselSlider.builder( {required this.itemCount, required this.itemBuilder, required this.options, this.disableGesture, CarouselSliderController? carouselController, Key? key}) : items = null, _carouselController = carouselController != null ? carouselController as CarouselSliderControllerImpl : CarouselSliderController() as CarouselSliderControllerImpl, super(key: key); ``` -------------------------------- ### CarouselState Methods and Operators Source: https://pub.dev/documentation/carousel_slider/latest/carousel_state/CarouselState-class This section covers the methods and operators available for the CarouselState class. It includes standard methods like `noSuchMethod` and `toString` inherited from Object, and the equality operator `==` for comparing instances. ```dart noSuchMethod(Invocation invocation) → dynamic tosString() → String operator ==(Object other) → bool ``` -------------------------------- ### CarouselSlider Methods Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider-class Outlines the key methods of the CarouselSlider class, such as 'createState' for creating the mutable state object, and diagnostic methods like 'debugDescribeChildren' and 'debugFillProperties' for debugging purposes. ```dart StatefulElement createElement() CarouselSliderState createState() List debugDescribeChildren() void debugFillProperties(DiagnosticPropertiesBuilder properties) dynamic noSuchMethod(Invocation invocation) DiagnosticsNode toDiagnosticsNode({String? name, DiagnosticTreeStyle? style}) String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) String toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) String toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) String toStringShort() ``` -------------------------------- ### CarouselSliderController Constructors and Methods - Dart Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderController-class This snippet details the constructor and various methods of the CarouselSliderController class. It includes methods for initializing the controller, animating to specific pages, controlling autoplay, and handling non-existent method calls. ```dart class CarouselSliderController { // Constructor CarouselSliderController.new(); // Properties Future onReady; bool ready; Type runtimeType; // Methods Future animateToPage(int page, {Duration? duration, Curve? curve}) { // Implementation details... return Future.value(); } void jumpToPage(int page) { // Implementation details... } Future nextPage({Duration? duration, Curve? curve}) { // Implementation details... return Future.value(); } dynamic noSuchMethod(Invocation invocation) { // Implementation details... return null; } Future previousPage({Duration? duration, Curve? curve}) { // Implementation details... return Future.value(); } void startAutoPlay() { // Implementation details... } void stopAutoPlay() { // Implementation details... } String toString() { // Implementation details... return super.toString(); } } class CarouselSliderControllerImpl implements CarouselSliderController { // Implementations for CarouselSliderController methods and properties @override Future get onReady => throw UnimplementedError(); @override bool get ready => throw UnimplementedError(); @override Type get runtimeType => throw UnimplementedError(); @override Future animateToPage(int page, {Duration? duration, Curve? curve}) { // TODO: implement animateToPage throw UnimplementedError(); } @override void jumpToPage(int page) { // TODO: implement jumpToPage } @override Future nextPage({Duration? duration, Curve? curve}) { // TODO: implement nextPage throw UnimplementedError(); } @override dynamic noSuchMethod(Invocation invocation) { // TODO: implement noSuchMethod throw UnimplementedError(); } @override Future previousPage({Duration? duration, Curve? curve}) { // TODO: implement previousPage throw UnimplementedError(); } @override void startAutoPlay() { // TODO: implement startAutoPlay } @override void stopAutoPlay() { // TODO: implement stopAutoPlay } @override String toString() { // TODO: implement toString return super.toString(); } @override int get hashCode => super.hashCode; @override operator ==(Object other) => super == other; } ``` -------------------------------- ### CarouselState Properties Source: https://pub.dev/documentation/carousel_slider/latest/carousel_state/CarouselState-class This section details the various properties of the CarouselState class. These include configuration options like `initialPage`, `itemCount`, and `options`, as well as control and state-related properties such as `pageController`, `realPage`, and callback functions for timer and mode management (`onResetTimer`, `onResumeTimer`, `changeMode`). ```dart changeMode ↔ dynamic Function(CarouselPageChangedReason) initialPage ↔ int itemCount ↔ int? onResetTimer ↔ FunctiononResumeTimer ↔ Function options ↔ CarouselOptions pageController ↔ PageController? realPage ↔ int ``` -------------------------------- ### CarouselSlider nextPage Method Implementation (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderControllerImpl/nextPage This Dart code implements the nextPage method for a CarouselSlider. It animates the slider to the next page, optionally resetting the auto-play timer if configured. The animation duration and curve are configurable. It relies on internal state management and a PageController. ```dart Future nextPage( {Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear}) async { final bool isNeedResetTimer = _state!.options.pauseAutoPlayOnManualNavigate; if (isNeedResetTimer) { _state!.onResetTimer(); } _setModeController(); await _state!.pageController!.nextPage(duration: duration!, curve: curve!); if (isNeedResetTimer) { _state!.onResumeTimer(); } } ``` -------------------------------- ### CarouselSlider didUpdateWidget Implementation (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/didUpdateWidget This snippet shows the implementation of the didUpdateWidget method for a CarouselSlider. It updates the carousel's options and item count, re-initializes the pageController, and handles autoplay when the widget configuration changes. It ensures to call the super method for proper inheritance. ```dart @override void didUpdateWidget(CarouselSlider oldWidget) { carouselState!.options = options; carouselState!.itemCount = widget.itemCount; // pageController needs to be re-initialized to respond to state changes pageController = PageController( viewportFraction: options.viewportFraction, initialPage: carouselState!.realPage, ); carouselState!.pageController = pageController; // handle autoplay when state changes handleAutoPlay(); super.didUpdateWidget(oldWidget); } ``` -------------------------------- ### Implement Timer for Carousel Auto-Play (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/getTimer This Dart code implements the getTimer method, which sets up a periodic timer for auto-playing the carousel. It handles mounted status, route visibility, page transitions, and options for infinite scrolling and pausing auto-play. ```dart Timer? getTimer() { return widget.options.autoPlay ? Timer.periodic(widget.options.autoPlayInterval, (_) { if (!mounted) { clearTimer(); return; } final route = ModalRoute.of(context); if (route?.isCurrent == false) { return; } CarouselPageChangedReason previousReason = mode; changeMode(CarouselPageChangedReason.timed); int nextPage = carouselState!.pageController!.page!.round() + 1; int itemCount = widget.itemCount ?? widget.items!.length; if (nextPage >= itemCount && widget.options.enableInfiniteScroll == false) { if (widget.options.pauseAutoPlayInFiniteScroll) { clearTimer(); return; } nextPage = 0; } carouselState!.pageController! .animateToPage(nextPage, duration: widget.options.autoPlayAnimationDuration, curve: widget.options.autoPlayCurve) .then((_) => changeMode(previousReason)); }) : null; } ``` -------------------------------- ### Dart CarouselOptions Constructor Definition Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselOptions/CarouselOptions Defines the default constructor for the CarouselOptions class in Dart. This constructor allows for extensive customization of carousel slider properties, including size, scrolling behavior, animation, autoplay settings, and event callbacks. ```dart CarouselOptions({ this.height, this.aspectRatio = 16 / 9, this.viewportFraction = 0.8, this.initialPage = 0, this.enableInfiniteScroll = true, this.animateToClosest = true, this.reverse = false, this.autoPlay = false, this.autoPlayInterval = const Duration(seconds: 4), this.autoPlayAnimationDuration = const Duration(milliseconds: 800), this.autoPlayCurve = Curves.fastOutSlowIn, this.enlargeCenterPage = false, this.onPageChanged, this.onScrolled, this.scrollPhysics, this.pageSnapping = true, this.scrollDirection = Axis.horizontal, this.pauseAutoPlayOnTouch = true, this.pauseAutoPlayOnManualNavigate = true, this.pauseAutoPlayInFiniteScroll = false, this.pageViewKey, this.enlargeStrategy = CenterPageEnlargeStrategy.scale, this.enlargeFactor = 0.3, this.disableCenter = false, this.padEnds = true, this.clipBehavior = Clip.hardEdge, }); ``` -------------------------------- ### CarouselSliderState createState Implementation in Dart Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider/createState This snippet shows the specific implementation of the createState method for the CarouselSliderState. It overrides the default behavior to return a CarouselSliderState instance, potentially initializing it with a controller. ```dart @override CarouselSliderState createState() => CarouselSliderState(_carouselController); ``` -------------------------------- ### Implement Gesture Wrapper with Scroll Handling (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/getGestureWrapper This Dart code defines the `getGestureWrapper` method, which takes a `Widget` as input and returns a wrapped `Widget`. It conditionally applies a `Container` or `AspectRatio` based on widget options and integrates `NotificationListener` for scroll events and `RawGestureDetector` for gesture handling. Dependencies include Flutter's `widgets.dart` and potentially custom gesture recognizers. ```dart Widget getGestureWrapper(Widget child) { Widget wrapper; if (widget.options.height != null) { wrapper = Container(height: widget.options.height, child: child); } else { wrapper = AspectRatio(aspectRatio: widget.options.aspectRatio, child: child); } if (true == widget.disableGesture) { return NotificationListener( onNotification: (Notification notification) { if (widget.options.onScrolled != null && notification is ScrollUpdateNotification) { widget.options.onScrolled!(carouselState!.pageController!.page); } return false; }, child: wrapper, ); } return RawGestureDetector( behavior: HitTestBehavior.opaque, gestures: { _MultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<_MultipleGestureRecognizer>( () => _MultipleGestureRecognizer(), (_MultipleGestureRecognizer instance) { instance.onStart = (_) { onStart(); }; instance.onDown = (_) { onPanDown(); }; instance.onEnd = (_) { onPanUp(); }; instance.onCancel = () { onPanUp(); }; }), }, child: NotificationListener( onNotification: (Notification notification) { if (widget.options.onScrolled != null && notification is ScrollUpdateNotification) { widget.options.onScrolled!(carouselState!.pageController!.page); } return false; }, child: wrapper, ), ); } ``` -------------------------------- ### Flutter Carousel Slider Widget Build Method Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/build This Dart code defines the `build` method for a Flutter carousel slider widget. It configures a `PageView.builder` with various options for scrolling, animation, and item display. The `itemBuilder` dynamically applies transformations to carousel items, including scaling and adjusting height/width based on their position and the `enlargeCenterPage` option. It handles different scroll directions and RTL text layouts. ```dart @override Widget build(BuildContext context) { return getGestureWrapper(PageView.builder( padEnds: widget.options.padEnds, scrollBehavior: ScrollConfiguration.of(context).copyWith( scrollbars: false, overscroll: false, dragDevices: { PointerDeviceKind.touch, PointerDeviceKind.mouse, PointerDeviceKind.stylus, }, ), clipBehavior: widget.options.clipBehavior, physics: widget.options.scrollPhysics, scrollDirection: widget.options.scrollDirection, pageSnapping: widget.options.pageSnapping, controller: carouselState!.pageController, reverse: widget.options.reverse, itemCount: widget.options.enableInfiniteScroll ? null : widget.itemCount, key: widget.options.pageViewKey, onPageChanged: (int index) { int currentPage = getRealIndex(index + carouselState!.initialPage, carouselState!.realPage, widget.itemCount); if (widget.options.onPageChanged != null) { widget.options.onPageChanged!(currentPage, mode); } }, itemBuilder: (BuildContext context, int idx) { final int index = getRealIndex(idx + carouselState!.initialPage, carouselState!.realPage, widget.itemCount); return AnimatedBuilder( animation: carouselState!.pageController!, child: (widget.items != null) ? (widget.items!.isNotEmpty ? widget.items![index] : Container()) : ((widget.itemCount ?? 0) > 0 ? widget.itemBuilder!(context, index, idx) : const SizedBox.shrink()), builder: (BuildContext context, child) { double distortionValue = 1.0; // if `enlargeCenterPage` is true, we must calculate the carousel item's height // to display the visual effect double itemOffset = 0; if (widget.options.enlargeCenterPage != null && widget.options.enlargeCenterPage == true) { // pageController.page can only be accessed after the first build, // so in the first build we calculate the itemoffset manually var position = carouselState?.pageController?.position; if (position != null && position.hasPixels && position.hasContentDimensions) { var _page = carouselState?.pageController?.page; if (_page != null) { itemOffset = _page - idx; } } else { BuildContext storageContext = carouselState! .pageController!.position.context.storageContext; final double? previousSavedPosition = PageStorage.of(storageContext).readState(storageContext) as double?; if (previousSavedPosition != null) { itemOffset = previousSavedPosition - idx.toDouble(); } else { itemOffset = carouselState!.realPage.toDouble() - idx.toDouble(); } } // Check if the text direction is right-to-left (RTL) if (Directionality.of(context) == TextDirection.rtl) { // If RTL, invert the item offset itemOffset = -itemOffset; } final double enlargeFactor = options.enlargeFactor.clamp(0.0, 1.0); final num distortionRatio = (1 - (itemOffset.abs() * enlargeFactor)).clamp(0.0, 1.0); distortionValue = Curves.easeOut.transform(distortionRatio as double); } final double height = widget.options.height ?? MediaQuery.of(context).size.width * (1 / widget.options.aspectRatio); if (widget.options.scrollDirection == Axis.horizontal) { return getCenterWrapper(getEnlargeWrapper(child, height: distortionValue * height, scale: distortionValue, itemOffset: itemOffset)); } else { return getCenterWrapper(getEnlargeWrapper(child, width: distortionValue * MediaQuery.of(context).size.width, scale: distortionValue, itemOffset: itemOffset)); } }, ); }, )); } ``` -------------------------------- ### CarouselSliderController Methods Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider Lists the available methods for manually controlling a CarouselSlider using a CarouselSliderController. These methods allow for animating or jumping to specific pages, or navigating to the next/previous page. ```dart // .nextPage({Duration duration, Curve curve}) // Animate to the next page // .previousPage({Duration duration, Curve curve}) // Animate to the previous page // .jumpToPage(int page) // Jump to the given page. // .animateToPage(int page, {Duration duration, Curve curve}) // Animate to the given page. ``` -------------------------------- ### Implement jumpToPage Method in CarouselSlider Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderControllerImpl/jumpToPage This implementation of the jumpToPage method programmatically changes the displayed page of the CarouselSlider. It calculates the correct target page and uses the underlying PageController to perform the jump, ensuring smooth transitions without animation. ```dart void jumpToPage(int page) { final index = getRealIndex(_state!.pageController!.page!.toInt(), _state!.realPage - _state!.initialPage, _state!.itemCount); _setModeController(); final int pageToJump = _state!.pageController!.page!.toInt() + page - index; return _state!.pageController!.jumpToPage(pageToJump); } ``` -------------------------------- ### CarouselSlider with On-Demand Item Building Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider Shows how to use CarouselSlider.builder for memory efficiency by building item widgets only when they are needed. This is useful for large lists or when item widgets are complex. It requires itemCount and an itemBuilder function. ```dart CarouselSlider.builder( itemCount: 15, itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) => Container( child: Text(itemIndex.toString()), ), ) ``` -------------------------------- ### CarouselSlider Properties Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider-class Details the essential properties of the CarouselSlider class, including 'items' or 'itemCount' for content, 'options' for customization, 'disableGesture' to control user interaction, and 'carouselController' for programmatic control. ```dart final List? items; final int? itemCount; final ExtendedIndexedWidgetBuilder? itemBuilder; final CarouselOptions options; final bool? disableGesture; final CarouselSliderController? carouselController; ``` -------------------------------- ### getRealIndex Function Implementation Source: https://pub.dev/documentation/carousel_slider/latest/utils/getRealIndex Implements the getRealIndex logic to calculate the real index in a smaller collection based on a position and base index from a larger collection. It handles the circular nature of collections by using the remainder operation. The function takes the current position, the base offset, and the length of the target collection as input. ```dart int getRealIndex(int position, int base, int? length) { final int offset = position - base; return remainder(offset, length); } ``` -------------------------------- ### Animate CarouselSlider to a Specific Page (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderControllerImpl/animateToPage Animates the controlled CarouselSlider from the current page to the given page. It accepts a duration and curve for the animation. Includes logic for infinite scroll and auto-play timer management. ```dart Future animateToPage(int page, {Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear}) async { final bool isNeedResetTimer = _state!.options.pauseAutoPlayOnManualNavigate; if (isNeedResetTimer) { _state!.onResetTimer(); } final index = getRealIndex(_state!.pageController!.page!.toInt(), _state!.realPage - _state!.initialPage, _state!.itemCount); int smallestMovement = page - index; if (_state!.options.enableInfiniteScroll && _state!.itemCount != null && _state!.options.animateToClosest) { if ((page - index).abs() > (page + _state!.itemCount! - index).abs()) { smallestMovement = page + _state!.itemCount! - index; } else if ((page - index).abs() > (page - _state!.itemCount! - index).abs()) { smallestMovement = page - _state!.itemCount! - index; } } _setModeController(); await _state!.pageController!.animateToPage( _state!.pageController!.page!.toInt() + smallestMovement, duration: duration!, curve: curve!); if (isNeedResetTimer) { _state!.onResumeTimer(); } } ``` -------------------------------- ### CarouselPageChangedReason Enum Properties Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselPageChangedReason Lists the properties available for the CarouselPageChangedReason enum. Properties include hashCode, index, name, and runtimeType, with some inherited from the base Enum class. ```dart hashCode → int index → int name → String runtimeType → Type ``` -------------------------------- ### CarouselOptions copyWith Method Implementation (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselOptions/copyWith This Dart code snippet shows the implementation of the copyWith method for the CarouselOptions class. It allows creating a new instance of CarouselOptions with specific properties overridden, while keeping the rest of the properties from the original instance. This is a standard pattern for immutable objects in Dart. ```dart CarouselOptions copyWith( {double? height, double? aspectRatio, double? viewportFraction, int? initialPage, bool? enableInfiniteScroll, bool? reverse, bool? autoPlay, Duration? autoPlayInterval, Duration? autoPlayAnimationDuration, Curve? autoPlayCurve, bool? enlargeCenterPage, Function(int index, CarouselPageChangedReason reason)? onPageChanged, ValueChanged? onScrolled, ScrollPhysics? scrollPhysics, bool? pageSnapping, Axis? scrollDirection, bool? pauseAutoPlayOnTouch, bool? pauseAutoPlayOnManualNavigate, bool? pauseAutoPlayInFiniteScroll, PageStorageKey? pageViewKey, CenterPageEnlargeStrategy? enlargeStrategy, double? enlargeFactor, bool? disableCenter, Clip? clipBehavior, bool? padEnds}) => CarouselOptions( height: height ?? this.height, aspectRatio: aspectRatio ?? this.aspectRatio, viewportFraction: viewportFraction ?? this.viewportFraction, initialPage: initialPage ?? this.initialPage, enableInfiniteScroll: enableInfiniteScroll ?? this.enableInfiniteScroll, reverse: reverse ?? this.reverse, autoPlay: autoPlay ?? this.autoPlay, autoPlayInterval: autoPlayInterval ?? this.autoPlayInterval, autoPlayAnimationDuration: autoPlayAnimationDuration ?? this.autoPlayAnimationDuration, autoPlayCurve: autoPlayCurve ?? this.autoPlayCurve, enlargeCenterPage: enlargeCenterPage ?? this.enlargeCenterPage, onPageChanged: onPageChanged ?? this.onPageChanged, onScrolled: onScrolled ?? this.onScrolled, scrollPhysics: scrollPhysics ?? this.scrollPhysics, pageSnapping: pageSnapping ?? this.pageSnapping, scrollDirection: scrollDirection ?? this.scrollDirection, pauseAutoPlayOnTouch: pauseAutoPlayOnTouch ?? this.pauseAutoPlayOnTouch, pauseAutoPlayOnManualNavigate: pauseAutoPlayOnManualNavigate ?? this.pauseAutoPlayOnManualNavigate, pauseAutoPlayInFiniteScroll: pauseAutoPlayInFiniteScroll ?? this.pauseAutoPlayInFiniteScroll, pageViewKey: pageViewKey ?? this.pageViewKey, enlargeStrategy: enlargeStrategy ?? this.enlargeStrategy, enlargeFactor: enlargeFactor ?? this.enlargeFactor, disableCenter: disableCenter ?? this.disableCenter, clipBehavior: clipBehavior ?? this.clipBehavior, padEnds: padEnds ?? this.padEnds, ); ``` -------------------------------- ### Implement getEnlargeWrapper for Carousel Slider (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSliderState/getEnlargeWrapper This method adjusts the child widget's size and transformation based on the selected enlargement strategy. It handles different scaling and alignment for 'height' and 'zoom' strategies, requiring parameters like child widget, dimensions, scale, and item offset. The default behavior falls back to a simple scaling transformation. ```dart Widget getEnlargeWrapper(Widget? child, {double? width, double? height, double? scale, required double itemOffset}) { if (widget.options.enlargeStrategy == CenterPageEnlargeStrategy.height) { return SizedBox(child: child, width: width, height: height); } if (widget.options.enlargeStrategy == CenterPageEnlargeStrategy.zoom) { late Alignment alignment; final bool horizontal = options.scrollDirection == Axis.horizontal; if (itemOffset > 0) { alignment = horizontal ? Alignment.centerRight : Alignment.bottomCenter; } else { alignment = horizontal ? Alignment.centerLeft : Alignment.topCenter; } return Transform.scale(child: child, scale: scale!, alignment: alignment); } return Transform.scale( scale: scale!, child: Container(child: child, width: width, height: height)); } ``` -------------------------------- ### CarouselPageChangedReason Enum Constants Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselPageChangedReason Provides the constant list of all possible values for the CarouselPageChangedReason enum. This list is ordered according to the declaration of the enum values. ```dart values → const List ``` -------------------------------- ### Animate to Previous Page in CarouselSlider (Dart) Source: https://pub.dev/documentation/carousel_slider/latest/carousel_controller/CarouselSliderControllerImpl/previousPage This Dart implementation of the previousPage method animates the CarouselSlider to the previous page. It optionally resets the autoplay timer if configured to pause on manual navigation. The animation's duration and curve are customizable. The method returns a Future that completes when the animation is finished. ```dart Future previousPage({ Duration? duration = const Duration(milliseconds: 300), Curve? curve = Curves.linear, }) async { final bool isNeedResetTimer = _state!.options.pauseAutoPlayOnManualNavigate; if (isNeedResetTimer) { _state!.onResetTimer(); } _setModeController(); await _state!.pageController! .previousPage(duration: duration!, curve: curve!); if (isNeedResetTimer) { _state!.onResumeTimer(); } } ``` -------------------------------- ### CarouselPageChangedReason Enum Methods and Operators Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselPageChangedReason Details the methods and operators associated with the CarouselPageChangedReason enum. This includes the noSuchMethod and toString methods, and the equality operator (==), most of which are inherited. ```dart noSuchMethod(Invocation invocation) → dynamic tostring() → String operator ==(Object other) → bool ``` -------------------------------- ### Import carousel_slider Package in Dart Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider This snippet shows how to import the carousel_slider package into your Dart project. Ensure the package is added to your pubspec.yaml dependencies. ```dart import 'package:carousel_slider/carousel_slider.dart'; ``` -------------------------------- ### Controlling CarouselSlider Manually with CarouselSliderController Source: https://pub.dev/documentation/carousel_slider/latest/packages/carousel_slider Demonstrates how to use CarouselSliderController to programmatically control the carousel's position. This involves creating a controller instance, passing it to the CarouselSlider, and then calling methods like nextPage, previousPage, jumpToPage, or animateToPage. ```dart class CarouselDemo extends StatelessWidget { CarouselSliderController buttonCarouselController = CarouselSliderController(); @override Widget build(BuildContext context) => Column( children: [ CarouselSlider( items: child, carouselController: buttonCarouselController, options: CarouselOptions( autoPlay: false, enlargeCenterPage: true, viewportFraction: 0.9, aspectRatio: 2.0, initialPage: 2, ), ), RaisedButton( onPressed: () => buttonCarouselController.nextPage( duration: Duration(milliseconds: 300), curve: Curves.linear), child: Text('→'), ) ] ); } ``` -------------------------------- ### CarouselSlider Operators Source: https://pub.dev/documentation/carousel_slider/latest/carousel_slider/CarouselSlider-class Documents the overloaded equality operator '==' for the CarouselSlider class, which is inherited from the Object class and used for comparing instances. ```dart bool operator ==(Object other) ``` -------------------------------- ### CarouselPageChangedReason Enum Values Source: https://pub.dev/documentation/carousel_slider/latest/carousel_options/CarouselPageChangedReason Defines the possible reasons for a page change in a carousel. These include manual user interaction, automatic timed transitions, or changes initiated by a controller. ```dart timed → const CarouselPageChangedReason manual → const CarouselPageChangedReason controller → const CarouselPageChangedReason ```