You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何为carousel_slider轮播图的每张图片下方添加对应文本

核心修改点

  • 遍历图片列表时同时获取索引,实现图片与说明文本的一一绑定
  • 将说明文本嵌入每张轮播图的底部渐变容器中,固定显示在图片下方
  • 修正原代码所有轮播项共用当前选中索引读取文本的逻辑错误
  • 确保names数组长度与imgList一致,避免索引越界

修改后完整代码

import 'dart:ui';

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

class With extends StatefulWidget {
  var Fruit = [
    'apple',
    'banana',
    'orange',
    'kiwi',
    'dragon fruit',
    'mango',
    'grapes',
  ];

  // 补全第7项说明,和imgList长度一致
  final List<String> names = [
    'Banana',
    'Orange',
    'Apple',
    'Kiwi',
    'Dragon fruit',
    'Mango',
    'Grapes'
  ];

  final List<String> imgList = [
    'https://www.verywellfit.com/thmb/a4580FjTjbub9q4kI5m9X-Po-p0=/2002x1334/filters:no_upscale():max_bytes(150000):strip_icc()/Bananas-5c6a36a346e0fb0001f0e4a3.jpg',
    'https://thumbs.dreamstime.com/b/orange-fruit-green-leaves-isolated-white-background-clipping-path-full-depth-field-fresh-177726692.jpg',
    'http://www.macdentalcare.com/pub/photo/2014-09-apple.jpg',
    'https://s3.envato.com/files/249849777/131.jpg',
    'https://i.pinimg.com/736x/53/5b/39/535b39b71fcf75886ef16d11f41ad29c.jpg',
    'https://media.istockphoto.com/photos/three-mangos-on-a-white-background-picture-id183134675?k=20&m=183134675&s=170667a&w=0&h=vADItDDbx2x19BxrNU4sJyqKLECQRs3sCnOA9KCTihw=',
    'https://t4.ftcdn.net/jpg/03/01/98/69/360_F_301986993_SYvMrcYECPje0HK6qRQQcm6uC7d3tpVC.jpg',
  ];

  @override
  _WithState createState() => _WithState();
}

class _WithState extends State<With> {
  int _current = 0;

  @override
  Widget build(BuildContext context) {
    final List<Widget> imageSliders = widget.imgList
        .asMap()
        .entries
        .map(
          (entry) => Container(
            height: 200,
            width: 100,
            child: ClipRRect(
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                child: Stack(
                  children: <Widget>[
                    Image.network(
                      entry.value,
                      fit: BoxFit.cover,
                      height: 400,
                      width: 300,
                    ),
                    Positioned(
                      bottom: 0.0,
                      left: 0.0,
                      right: 0.0,
                      child: Container(
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.2),
                              spreadRadius: 5,
                              blurRadius: 10,
                              offset: Offset(5, 3),
                            ),
                          ],
                          gradient: LinearGradient(
                            colors: [
                              Color.fromARGB(180, 10, 100, 10),
                              Color.fromARGB(0, 0, 100, 0),
                            ],
                            begin: Alignment.bottomCenter,
                            end: Alignment.topCenter,
                          ),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 20,
                          vertical: 15,
                        ),
                        // 说明文本放在底部渐变容器内
                        child: Text(
                          widget.names[entry.key],
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        )
        .toList();

    return Column(
      children: [
        Padding(
          padding: EdgeInsets.all(10),
          child: Text(
            'FRUITS',
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
        ),
        CarouselSlider(
          items: imageSliders,
          options: CarouselOptions(
              viewportFraction: 0.4,
              autoPlay: false,
              enlargeCenterPage: true,
              pageSnapping: true,
              disableCenter: true,
              aspectRatio: 2.0,
              onPageChanged: (index, reason) {
                setState(() {
                  _current = index;
                });
              }),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widget.imgList.map((url) {
            int index = widget.imgList.indexOf(url);
            return Container(
              width: 5,
              height: 5,
              margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index
                      ? Color.fromRGBO(0, 0, 0, 0.9)
                      : Color.fromRGBO(0, 0, 0, 0.4)),
            );
          }).toList(),
        )
      ],
    );
  }
}

关键逻辑说明

原代码中直接遍历imgList无法获取对应索引,导致无法绑定对应说明文本,改用asMap().entries.map后可以同时拿到每个轮播项的索引entry.key和图片地址entry.value,直接通过索引读取names数组的对应值即可实现每张图片显示对应说明的效果。同时调整了底部渐变容器的透明度和内边距,优化了文本显示效果。

内容的提问来源于stack exchange,提问作者recharla joshitha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:06:03