Flutter carousel_slider 幻灯片播放

本文详细介绍了如何在Flutter应用中使用carousel_slider插件创建并实现一个带有自动播放功能的幻灯片组件,包括组件安装、数据定义、组件添加和小点点控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

carousel_slider 插件 幻灯片播放

在这里插入图片描述

  1. 安装插件
flutter pub add carousel_slider
  1. 导入包
import 'package:carousel_slider/carousel_slider.dart';
  1. 定义数据
 //当前图片索引
 int _current = 0; 
 //小点点控制
 final CarouselController _controller = CarouselController();
 //图片列表
 List<String> list = [
    'https://p1.ssl.qhimg.com/t01683f3a068943c2e3.png',
    'https://p1.ssl.qhimg.com/t01e9ee778759020ddb.png',
    'https://p1.ssl.qhimg.com/t01f7dfb7391d1f1de2.jpg',
    'https://p1.ssl.qhimg.com/t01aa65ca167724f2c9.jpg',
    'https://p4.ssl.qhimg.com/t01345cf34a1807d669.png'
  ];
  1. 添加组件
CarouselSlider.builder(
          carouselController: _controller,
          options: CarouselOptions(
            height: 150,
            autoPlay: true,
            viewportFraction: 1.0,
            autoPlayInterval: const Duration(seconds: 1),
            onPageChanged: (index, reason) {
              setState(() {
                _current = index;
              });
            },
          ),
          itemCount: list.length,
          itemBuilder: (BuildContext context, int index, int pageViewIndex) {
            return GestureDetector(
              onTap: () {
                print("点我了");
              },
              child: Image.network(list[index], fit: BoxFit.cover),
            );
          },
        )
  1. 添加小点点组件
list.asMap().entries.map((entry) {
            return GestureDetector(
              onTap: () => _controller.animateToPage(entry.key),
              child: Container(
                width: 10.0,
                height: 10.0,
                margin:
                    const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: (Theme.of(context).brightness == Brightness.dark
                            ? Colors.white
                            : Colors.black)
                        .withOpacity(_current == entry.key ? 0.9 : 0.4)),
              ),
            );
          }).toList(),
  1. 完整代码
//File: ComponentSlider.dart

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

class ComponentSlider extends StatefulWidget {
  const ComponentSlider({Key? key}) : super(key: key);

  
  State<ComponentSlider> createState() => _ComponentSliderState();
}

class _ComponentSliderState extends State<ComponentSlider> {
  int _current = 0;
  final CarouselController _controller = CarouselController();

  List<String> list = [
    'https://p1.ssl.qhimg.com/t01683f3a068943c2e3.png',
    'https://p1.ssl.qhimg.com/t01e9ee778759020ddb.png',
    'https://p1.ssl.qhimg.com/t01f7dfb7391d1f1de2.jpg',
    'https://p1.ssl.qhimg.com/t01aa65ca167724f2c9.jpg',
    'https://p4.ssl.qhimg.com/t01345cf34a1807d669.png'
  ];

  
  Widget build(BuildContext context) {
    return Stack(
      alignment: AlignmentDirectional.bottomCenter,
      children: [
        CarouselSlider.builder(
          carouselController: _controller,
          options: CarouselOptions(
            height: 150,
            autoPlay: true,
            viewportFraction: 1.0,
            autoPlayInterval: const Duration(seconds: 1),
            onPageChanged: (index, reason) {
              setState(() {
                _current = index;
              });
            },
          ),
          itemCount: list.length,
          itemBuilder: (BuildContext context, int index, int pageViewIndex) {
            return GestureDetector(
              onTap: () {
                print("点我了");
              },
              child: Image.network(list[index], fit: BoxFit.cover),
            );
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: list.asMap().entries.map((entry) {
            return GestureDetector(
              onTap: () => _controller.animateToPage(entry.key),
              child: Container(
                width: 10.0,
                height: 10.0,
                margin:
                    const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: (Theme.of(context).brightness == Brightness.dark
                            ? Colors.white
                            : Colors.black)
                        .withOpacity(_current == entry.key ? 0.9 : 0.4)),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

  1. 可选项参数 options: CarouselOptions()

enum CarouselPageChangedReason { timed, manual, controller }

enum CenterPageEnlargeStrategy { scale, height, zoom }

class CarouselOptions {
  /// Set carousel height and overrides any existing [aspectRatio].
  final double? height;

  /// Aspect ratio is used if no height have been declared.
  ///
  /// Defaults to 16:9 aspect ratio.
  final double aspectRatio;

  /// The fraction of the viewport that each page should occupy.
  ///
  /// Defaults to 0.8, which means each page fills 80% of the carousel.
  final double viewportFraction;

  /// The initial page to show when first creating the [CarouselSlider].
  ///
  /// Defaults to 0.
  final int initialPage;

  ///Determines if carousel should loop infinitely or be limited to item length.
  ///
  ///Defaults to true, i.e. infinite loop.
  final bool enableInfiniteScroll;

  ///Determines if carousel should loop to the closest occurence of requested page.
  ///
  ///Defaults to true.
  final bool animateToClosest;

  /// Reverse the order of items if set to true.
  ///
  /// Defaults to false.
  final bool reverse;

  /// Enables auto play, sliding one page at a time.
  ///
  /// Use [autoPlayInterval] to determent the frequency of slides.
  /// Defaults to false.
  final bool autoPlay;

  /// Sets Duration to determent the frequency of slides when
  ///
  /// [autoPlay] is set to true.
  /// Defaults to 4 seconds.
  final Duration autoPlayInterval;

  /// The animation duration between two transitioning pages while in auto playback.
  ///
  /// Defaults to 800 ms.
  final Duration autoPlayAnimationDuration;

  /// Determines the animation curve physics.
  ///
  /// Defaults to [Curves.fastOutSlowIn].
  final Curve autoPlayCurve;

  /// Determines if current page should be larger than the side images,
  /// creating a feeling of depth in the carousel.
  ///
  /// Defaults to false.
  final bool? enlargeCenterPage;

  /// The axis along which the page view scrolls.
  ///
  /// Defaults to [Axis.horizontal].
  final Axis scrollDirection;

  /// Called whenever the page in the center of the viewport changes.
  final Function(int index, CarouselPageChangedReason reason)? onPageChanged;

  /// Called whenever the carousel is scrolled
  final ValueChanged<double?>? onScrolled;

  /// How the carousel should respond to user input.
  ///
  /// For example, determines how the items continues to animate after the
  /// user stops dragging the page view.
  ///
  /// The physics are modified to snap to page boundaries using
  /// [PageScrollPhysics] prior to being used.
  ///
  /// Defaults to matching platform conventions.
  final ScrollPhysics? scrollPhysics;

  /// Set to false to disable page snapping, useful for custom scroll behavior.
  ///
  /// Default to `true`.
  final bool pageSnapping;

  /// 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 bool pauseAutoPlayOnTouch;

  /// 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 bool pauseAutoPlayOnManualNavigate;

  /// 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 bool pauseAutoPlayInFiniteScroll;

  /// Pass a `PageStoragekey` if you want to keep the pageview's position when it was recreated.
  final PageStorageKey? pageViewKey;

  /// Use [enlargeStrategy] to determine which method to enlarge the center page.
  final CenterPageEnlargeStrategy enlargeStrategy;

  /// How much the pages next to the center page will be scaled down.
  /// If `enlargeCenterPage` is false, this property has no effect.
  final double enlargeFactor;

  /// Whether or not to disable the `Center` widget for each slide.
  final bool disableCenter;

  /// 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 bool padEnds;

  /// Exposed clipBehavior of PageView
  final Clip clipBehavior;

  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,
  });

标题内容转载:https://www.fluttericon.cn

### 如何在 Flutter 中使用 CarouselView 组件 #### 安装依赖包 为了能够在项目中使用 `flutter_carousel_slider`,需要先将其添加到项目的 `pubspec.yaml` 文件中的 dependencies 部分。 ```yaml dependencies: flutter: sdk: flutter flutter_carousel_slider: ^latest_version ``` 之后运行命令来安装这个插件: ```bash flutter pub get ``` #### 创建简单的轮播图实例 下面是一个创建简单轮播图的例子,在此例子中会展示如何初始化并配置基本属性[^1]。 ```dart import 'package:flutter/material.dart'; import 'package:flutter_carousel_slider/carousel_slider.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Carousel Example')), body: Center(child: MyCarousel()), ), ); } } class MyCarousel extends StatefulWidget { @override _MyCarouselState createState() => _MyCarouselState(); } class _MyCarouselState extends State<MyCarousel> with SingleTickerProviderStateMixin { final List<String> imgList = [ 'https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg' ]; late CarouselSliderController _controller; @override void initState() { super.initState(); _controller = CarouselSliderController(); } @override Widget build(BuildContext context) { return Column( children: <Widget>[ Expanded( child: CarouselSlider.builder( unlimitedMode: true, slideBuilder: (index){ return Image.network(imgList[index], fit: BoxFit.cover); }, itemCount: imgList.length, controller: _controller, ) ), ], ); } } ``` 这段代码展示了如何设置无限模式下的图片滑动效果,并通过网络加载图像作为幻灯片的内容。同时设置了自定义控制器 `_controller` 来管理轮播行为。 #### 使用 Material Design 的 CarouselView 特性 如果想要利用更高级的功能如动态调整大小等,则可以考虑使用带有Material Design风格的 `CarouselView` 小部件[^2]。不过需要注意的是,上述提到的具体实现细节可能因具体库的不同而有所差异,请查阅官方文档获取最新指导。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值