import 'package:flutter/material.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:shared/utils/log_utils.dart'; import 'calendar_utils.dart'; import 'day_of_week_view.dart'; import 'day_table_view.dart'; /// 总入口,整合顶部的Week控件与底部的Days的PageView控件 class WeeklyCalendar extends StatefulWidget { const WeeklyCalendar({ super.key, this.onChangedSelectedDate, this.selectedDate, }); final DateTime? selectedDate; //当前选中的日期 final Function(DateTime)? onChangedSelectedDate; //选择日期的回调 @override State createState() => _WeeklyCalendarState(); } class _WeeklyCalendarState extends State { final DateTime now = DateTime.now(); DateTime? selectedDate; late List currentDateList; @override void initState() { initializeDateFormatting("en"); //日期国际化指定 super.initState(); currentDateList = get2Weekdays(now, 0); //双周的数据 selectedDate = widget.selectedDate ?? now; //默认选中的数据 } @override void didUpdateWidget(covariant WeeklyCalendar oldWidget) { super.didUpdateWidget(oldWidget); if (widget.selectedDate != oldWidget.selectedDate) { //查看当前页面Date数据是否包含选中的 selectedDate bool hasSelected = hasSelectedDate(currentDateList, widget.selectedDate ?? now); setState(() { selectedDate = widget.selectedDate; if (!hasSelected) { //如果不包含,需要更换数据源 Log.d("选中日期不在当前页面,需要更换数据源"); currentDateList = get2Weekdays(widget.selectedDate ?? now, 0); } }); } } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ //顶部是固定的星期布局 customDayOfWeek(), const SizedBox(height: 12), //底部是当前二周的数据 DayTableView( weekdays: currentDateList, onSelect: (date) { setState(() { selectedDate = date; }); //主动点击之后回调 widget.onChangedSelectedDate?.call(date); }, selectedDate: selectedDate ?? now, currentDate: now, ) ], ); } //星期的文本显示 Widget customDayOfWeek() { final weekdays = getWeekdays(now, 0); return DayOfWeekView(weekdays: weekdays); } }