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

Flutter实现跳过周六周日的指定数量工作日列表展示

解决Flutter中展示指定数量工作日日期列表的问题

核心思路是先预先生成符合要求的工作日日期列表,确保列表长度等于你需要展示的数量,再基于这个列表构建UI,避免直接按索引累加天数导致包含周末。

步骤1:添加生成工作日列表的方法

这个方法会从当前日期开始筛选工作日,直到收集到指定数量的日期:

List<DateTime> generateWorkdays(int count) {
  List<DateTime> workdays = [];
  DateTime currentDate = DateTime.now();
  while (workdays.length < count) {
    // 过滤周六(DateTime.saturday=6)和周日(DateTime.sunday=7)
    if (currentDate.weekday != DateTime.saturday && currentDate.weekday != DateTime.sunday) {
      workdays.add(currentDate);
    }
    currentDate = currentDate.add(const Duration(days: 1));
  }
  return workdays;
}

步骤2:初始化工作日列表

在你的页面初始化时生成需要的工作日列表(这里以展示7个为例):

final List<DateTime> workdayList = generateWorkdays(7);

步骤3:修改ListView和日期组件

更新ListView.builder,直接使用预生成的工作日列表;同时调整dateWidget方法,接收具体的DateTime对象而非索引:

修改后的ListView代码:

ListView.builder(
  itemCount: workdayList.length,
  shrinkWrap: true,
  itemBuilder: (context, index) => dateWidget(workdayList[index]),
),

修改后的dateWidget方法:

Widget dateWidget(DateTime date) {
  return InkWell(
    onTap: () {},
    child: Container(
      margin: const EdgeInsets.all(2),
      width: 10.0,
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        color: AppColor.premiumBlue,
      ),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            labels(text: DateFormat('EE').format(date).toUpperCase()),
            labels(
              text: date.day.toString(),
              color: AppColor.white,
            ),
          ],
        ),
      ),
    ),
  );
}

这样修改后,无论你设置多少展示数量,最终列表都会严格展示对应数量的工作日,自动跳过周六和周日,不足时自动补充后续的工作日。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:27:19