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

Flutter如何基于数组实现横向可滚动组件列表

Flutter 批量生成横向滚动年份列表实现方案

你不需要逐个手动编写列表项,只需要先把展示内容存入数组,再通过遍历批量生成组件即可,具体实现如下:

核心修改点

  • 把所有要展示的年份文本统一存在数组中,后续增删选项只需要修改数组内容,不需要调整布局代码
  • 替换Row中硬编码的ByYear组件,通过数组map方法批量转换为Widget列表
  • 可选优化:原代码中每个ByYear组件独立维护选中状态,且选中/未选中颜色重复、默认全部选中不符合常规交互,可一并优化点击切换、颜色区分、选项间距的逻辑

修改后可直接运行的代码

class YearSort extends StatelessWidget {
  final String title; 

  const YearSort({ 
    Key? key, 
    required this.title,
     }) : super(key: key);

  // 统一维护年份选项列表
  final List<String> yearOptions = const [
    'This year',
    '2021',
    '2020',
    '2019',
    '2018',
  ];

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView( 
      scrollDirection: Axis.horizontal, 
      child: Row( 
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        // 遍历数组批量生成所有年份选项组件
        children: yearOptions.map((yearText) => ByYear(year: yearText)).toList(),
      ),
    );
  }
}

class ByYear extends StatefulWidget {
  final String year;

  const ByYear({ 
    Key? key, 
    required this.year, 
  }) : super(key: key);

  @override
  State<ByYear> createState() => _ByYearState();
}

class _ByYearState extends State<ByYear> {
  // 默认未选中状态
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 点击切换选中状态
      onTap: () {
        setState(() {
          isSelected = !isSelected;
        });
      },
      child: Container(
        width: 100,
        height: 30,
        // 增加左右间距避免选项挤压
        margin: const EdgeInsets.symmetric(horizontal: 6),
        decoration: BoxDecoration(
          // 区分选中/未选中的背景色
          color: isSelected
              ? const Color.fromARGB(255, 215, 237, 255)
              : Colors.white,
          borderRadius: BorderRadius.circular(20), 
        ),
        child: Center(
          child: Text(
            widget.year, 
            style: const TextStyle(fontFamily: 'Poppins'),
          ),
        ),
      ),
    );
  }
}

扩展提示

  • 如果需要实现单选互斥效果(同一时间仅一个年份可选中),把选中状态上移到YearSort父组件维护即可,不需要每个子组件单独维护状态
  • 横向滚动逻辑不需要修改,SingleChildScrollView设置Axis.horizontal后,Row内容超出视口宽度会自动支持横向滑动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:01:06