如何在SfCalendar中仅启用startDate至endDate之间的时间段?
实现仅启用指定时间段,禁用其余时间
以下是修改后的完整代码,实现仅启用每日14:00-15:00的时间段,其余时间全部禁用:
import 'package:flutter/material.dart'; import 'package:syncfusion_flutter_calendar/calendar.dart'; class TestFile extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<TestFile> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('SfCalendar 时间段控制示例')), body: SfCalendar( initialDisplayDate: DateTime.now(), view: CalendarView.week, specialRegions: _getTimeRegions(), ), ); } List<TimeRegion> _getTimeRegions() { final List<TimeRegion> regions = <TimeRegion>[]; DateTime now = DateTime.now(); DateTime targetStartTime = DateTime(now.year, now.month, now.day, 14, 0, 0); DateTime targetEndTime = DateTime(now.year, now.month, now.day, 15, 0, 0); // 禁用当天00:00到目标时间段开始的区域 regions.add(TimeRegion( startTime: DateTime(now.year, now.month, now.day, 0, 0, 0), endTime: targetStartTime, color: Colors.grey.withOpacity(0.2), textStyle: TextStyle(color: Colors.black45, fontSize: 15), isDisabled: true, // 明确禁用该区域的交互 recurrenceRule: 'FREQ=DAILY;COUNT=7', // 覆盖一周,可根据需求调整COUNT值 )); // 禁用目标时间段结束到当天23:59:59的区域 regions.add(TimeRegion( startTime: targetEndTime, endTime: DateTime(now.year, now.month, now.day, 23, 59, 59), color: Colors.grey.withOpacity(0.2), textStyle: TextStyle(color: Colors.black45, fontSize: 15), isDisabled: true, // 明确禁用该区域的交互 recurrenceRule: 'FREQ=DAILY;COUNT=7', // 覆盖一周,可根据需求调整COUNT值 )); return regions; } }
关键修改说明:
- 拆分禁用区域:将原来单一的目标时间段禁用,改为创建两个覆盖非目标时间段的禁用区域,分别覆盖每日0点到14点、15点到24点的时间范围
- 明确禁用交互:添加
isDisabled: true属性,确保这些区域无法被选中或交互,比仅用颜色标记更规范 - 调整重复规则:将
recurrenceRule的COUNT设为7,适配CalendarView.week视图覆盖整周;如果只需要当天生效,可改回COUNT=1 - 视觉保持一致:禁用区域的颜色和文本样式保持与原代码一致,确保视觉上的区分度
内容的提问来源于stack exchange,提问作者Abbas Jafari
相关产品推荐
相关产品推荐

