Flutter动态轮播图插件dynamic_carousel的使用

Flutter动态轮播图插件dynamic_carousel的使用

预览

dynamic_carousel_preview

功能特性

Dynamic Carousel Widget 是一个带有缩放动画功能的轮播组件,可以动态添加和删除元素。

缩放动画
  • 聚焦时展开轮播项的缩放动画。
  • 从聚焦项旁边的部件到之前的部件进行缩放动画。
滚动条轮播
  • 自动可调的轮播滚动条。
  • 可定制的滚动条。
  • 当轮播项超过两个时显示滚动条小部件。
删除项
  • 从轮播中删除项,并实时更改它们。

开始使用

  1. 将包添加到yaml文件中:

    dynamic_carousel: latestversion
    
  2. 在使用之前导入包到你的部件树中:

    import 'package:dynamic_carousel/dynamic_carousel.dart';
    
  3. 示例代码加载默认属性的轮播:

    List<Widget> carouselItems = [
        Container(
            width: double.maxFinite,
            height: double.maxFinite,
            color: Colors.green, // 绿色背景
        ),
        Container(
            width: double.maxFinite,
            height: double.maxFinite,
            color: Colors.blue, // 蓝色背景
        ),
    ];
    
    DynamicCarousel(
        animationDuration: Duration(milliseconds: 250), // 动画持续时间
        onDelete: (index) {
            carouselItems.removeAt(index); // 删除指定索引的项目
        },
        children: carouselItems, // 子部件列表
    ),
    

使用方法

// 设置轮播滑块的属性
final properties = TrackBarProperties(
    trackbarColor: Colors.grey, // 设置滑块背景颜色
    sliderColor: Colors.orange, // 设置滑块的颜色
    sliderHeight: 10, // 设置滑块的高度
    trackbarLength: 150, // 设置滑块的水平长度
    topSpacing: 40, // 设置滑块与轮播之间的间距
);

// 轮播的部件列表
List<Widget> carouselItems = [
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.green, // 绿色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.red, // 红色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.blue, // 蓝色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.yellow, // 黄色背景
    ),
];

Widget build(BuildContext context){
    return DynamicCarousel(
        height: 400, // 轮播高度
        bigItemHeight: 400, // 大项高度
        bigItemWidth: 400, // 大项宽度
        smallItemWidth: 200, // 小项宽度
        smallItemHeight: 200, // 小项高度
        trackBarProperties: properties, // 滑块属性
        animationDuration: Duration(milliseconds: 100), // 动画持续时间
        onDeleteWidget: IconButton(onPressed: (){}, icon: Icon(Icons.remove)), // 定制删除图标
        onDelete: (int index){}, // 删除项回调
        children: carouselItems, // 子部件列表
    );
}

完整示例Demo

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dynamic Carousel Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Dynamic Carousel Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> carouselItems = [
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.green, // 绿色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.red, // 红色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.blue, // 蓝色背景
    ),
    Container(
      width: double.maxFinite,
      height: double.maxFinite,
      color: Colors.yellow, // 黄色背景
    ),
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const SizedBox(height: 20),
          const Text(
            'Dynamic Carousel',
          ),
          const SizedBox(height: 20),
          DynamicCarousel(
            animationDuration: Duration(milliseconds: 250), // 动画持续时间
            onDelete: (index) {
              setState(() {
                carouselItems.removeAt(index); // 删除指定索引的项目
              });
            },
            children: carouselItems, // 子部件列表
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                carouselItems.add(Container(
                  width: double.maxFinite,
                  height: double.maxFinite,
                  color: Colors.purple, // 添加紫色背景的新项
                ));
              });
            },
            child: const Text('Add Item'), // 添加新项按钮
          ),
        ],
      ),
    );
  }
}

更多关于Flutter动态轮播图插件dynamic_carousel的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动态轮播图插件dynamic_carousel的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用dynamic_carousel插件来实现动态轮播图的示例代码。dynamic_carousel插件允许你创建一个高度可定制的轮播图组件,非常适合展示图片或广告等内容。

首先,确保你的Flutter项目已经添加了dynamic_carousel依赖。在你的pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  dynamic_carousel: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来是示例代码,展示如何使用dynamic_carousel来创建一个动态轮播图:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dynamic Carousel Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> images = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic Carousel Demo'),
      ),
      body: Center(
        child: DynamicCarousel(
          images: images,
          width: double.infinity,
          height: 300,
          indicatorColor: Colors.white,
          indicatorActiveColor: Colors.blue,
          borderRadius: 16,
          autoPlay: true,
          autoPlayInterval: 3000,
          autoPlayAnimationDuration: 800,
          onImageClick: (index) {
            print('Image clicked at index: $index');
          },
          onPageChanged: (index) {
            print('Page changed to index: $index');
          },
        ),
      ),
    );
  }
}

代码解释

  1. 依赖导入

    • import 'package:flutter/material.dart';:导入Flutter的基础UI组件。
    • import 'package:dynamic_carousel/dynamic_carousel.dart';:导入dynamic_carousel插件。
  2. 应用入口

    • MyApp是一个无状态组件,用于设置应用的基本配置,如主题等。
  3. 主页

    • MyHomePage是一个有状态组件,包含轮播图所需的图片列表。
    • build方法中,返回一个Scaffold,包含一个应用栏和一个居中的DynamicCarousel组件。
  4. 轮播图配置

    • images:图片列表,可以是网络图片URL或本地资源路径。
    • widthheight:设置轮播图的宽度和高度。
    • indicatorColorindicatorActiveColor:设置指示器(小圆点)的颜色和选中时的颜色。
    • borderRadius:设置轮播图的圆角半径。
    • autoPlay:是否自动播放。
    • autoPlayInterval:自动播放的时间间隔(毫秒)。
    • autoPlayAnimationDuration:自动播放时的动画持续时间(毫秒)。
    • onImageClick:点击图片时的回调。
    • onPageChanged:页面改变时的回调。

这样,你就可以在Flutter项目中实现一个动态轮播图了。根据实际需求,你可以进一步自定义和扩展这个示例。

回到顶部