Flutter date_picker_timeline控件:设置本周日期显示及自动切换下周
解决方案
1. 限制显示范围为「今日至本周日」并禁用过往日期
该库没有直接的范围配置参数,但可以通过手动生成指定日期列表来实现:
首先添加两个辅助函数计算日期范围:
// 获取本周日的结束时间(23:59:59) DateTime _getEndOfWeek() { final now = DateTime.now(); // 计算距离本周日的天数(周日的weekday为7) final daysUntilSunday = DateTime.sunday - now.weekday; return now.add(Duration(days: daysUntilSunday)).copyWith(hour: 23, minute: 59, second: 59); } // 生成从今日到本周日的日期列表 List<DateTime> _generateDateRange() { final startDate = DateTime.now().copyWith(hour: 0, minute: 0, second: 0); final endDate = _getEndOfWeek(); final dates = <DateTime>[]; var currentDate = startDate; while (currentDate.isBefore(endDate) || currentDate.isAtSameMomentAs(endDate)) { dates.add(currentDate); currentDate = currentDate.add(const Duration(days: 1)); } return dates; }
然后修改DatePicker代码,通过dates参数传入生成的日期列表,这样就只会显示今日到本周日的日期,过往日期不会出现在时间线中:
// 在State类中定义变量 late List<DateTime> _displayDates; late Timer? _refreshTimer; @override void initState() { super.initState(); _displayDates = _generateDateRange(); } @override void dispose() { _refreshTimer?.cancel(); super.dispose(); } // 构建部分 Container( child: DatePicker( DateTime.now(), width: 60, height: 80, controller: _controller, initialSelectedDate: DateTime.now(), selectionColor: Colors.black, selectedTextColor: Colors.white, dates: _displayDates, // 传入自定义日期列表 onDateChange: (date) { setState(() { _selectedValue = date; }); }, ), )
2. 周日下午自动刷新显示下周日期
通过定时检查当前时间,当触发周日下午的条件时,重新生成下周的日期列表并更新状态:
在initState中添加定时任务:
@override void initState() { super.initState(); _displayDates = _generateDateRange(); // 每分钟检查一次时间 _refreshTimer = Timer.periodic(const Duration(minutes: 1), (timer) { final now = DateTime.now(); // 判断是否为周日且时间在12点及以后 if (now.weekday == DateTime.sunday && now.hour >= 12) { // 检查当前显示的最后日期是否为本周日,如果是则更新为下周 final currentEndDate = _getEndOfWeek(); if (_displayDates.last.isAtSameMomentAs(currentEndDate)) { setState(() { _displayDates = _generateDateRange(); }); } } }); }
说明
- 手动生成日期列表可以精确控制时间线显示的范围,同时天然屏蔽了过往日期的选择可能
- 定时任务采用每分钟检查一次的策略,平衡了实时性和性能开销,你也可以根据需求调整检查间隔
- 刷新时会自动更新状态,时间线会重新渲染为下周的日期范围
内容的提问来源于stack exchange,提问作者Hieu Trung
相关产品推荐
相关产品推荐

