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

Flutter使用card_swiper时如何将左侧组件设置为聚焦项

解决方案

你可以通过调整card_swiper的内置配置参数直接实现该需求,无需修改库源码:

  • 核心配置将alignment属性设为Alignment.centerLeft,指定滑动容器的对齐基准靠左,当前选中的聚焦项会默认停靠在左侧位置
  • 搭配viewportFraction设置为0.7~0.9的数值,保证聚焦项在左侧展示的同时,右侧可以露出后续卡片
  • 调整scale参数设置非聚焦项的缩小比例,进一步区分聚焦/非聚焦项的视觉差异

如果需要自定义聚焦项的高亮样式(比如你需求中的黄色背景),可以通过onIndexChanged回调监听当前选中下标,自行给对应下标的卡片添加高亮样式即可。

示例代码

int _currentIndex = 0;

@override
Widget build(BuildContext context) {
  return Swiper(
    itemCount: 10,
    // 核心配置:左对齐停靠
    alignment: Alignment.centerLeft,
    // 视窗比例,调整可控制露出的后续卡片宽度
    viewportFraction: 0.8,
    // 非聚焦项缩放比例
    scale: 0.85,
    // 非聚焦项透明度,可按需开启
    // opacity: 0.8,
    itemBuilder: (context, index) {
      return Container(
        // 自定义聚焦项高亮样式
        color: index == _currentIndex ? Colors.yellow : Colors.white,
        margin: const EdgeInsets.symmetric(horizontal: 8),
        child: Center(child: Text('卡片 $index')),
      );
    },
    onIndexChanged: (index) {
      setState(() {
        _currentIndex = index;
      });
    },
  );
}

如果你使用的是不支持alignment属性的旧版本card_swiper,可以改用堆叠布局实现:

  • 将layout设置为SwiperLayout.STACK
  • 配置stackAlignment: Alignment.centerLeft,同时调整stackOffset参数控制非聚焦项的偏移值即可

内容的提问来源于stack exchange,提问作者Khamidjon Khamidov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:54:03