weekly_calendar.dart 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import 'package:flutter/material.dart';
  2. import 'package:intl/date_symbol_data_local.dart';
  3. import 'package:shared/utils/log_utils.dart';
  4. import 'calendar_utils.dart';
  5. import 'day_of_week_view.dart';
  6. import 'day_table_view.dart';
  7. /// 总入口,整合顶部的Week控件与底部的Days的PageView控件
  8. class WeeklyCalendar extends StatefulWidget {
  9. const WeeklyCalendar({
  10. super.key,
  11. this.onChangedSelectedDate,
  12. this.selectedDate,
  13. });
  14. final DateTime? selectedDate; //当前选中的日期
  15. final Function(DateTime)? onChangedSelectedDate; //选择日期的回调
  16. @override
  17. State<StatefulWidget> createState() => _WeeklyCalendarState();
  18. }
  19. class _WeeklyCalendarState extends State<WeeklyCalendar> {
  20. final DateTime now = DateTime.now();
  21. DateTime? selectedDate;
  22. late List<DateTime> currentDateList;
  23. @override
  24. void initState() {
  25. initializeDateFormatting("en"); //日期国际化指定
  26. super.initState();
  27. currentDateList = get2Weekdays(now, 0); //双周的数据
  28. selectedDate = widget.selectedDate ?? now; //默认选中的数据
  29. }
  30. @override
  31. void didUpdateWidget(covariant WeeklyCalendar oldWidget) {
  32. super.didUpdateWidget(oldWidget);
  33. if (widget.selectedDate != oldWidget.selectedDate) {
  34. //查看当前页面Date数据是否包含选中的 selectedDate
  35. bool hasSelected = hasSelectedDate(currentDateList, widget.selectedDate ?? now);
  36. setState(() {
  37. selectedDate = widget.selectedDate;
  38. if (!hasSelected) {
  39. //如果不包含,需要更换数据源
  40. Log.d("选中日期不在当前页面,需要更换数据源");
  41. currentDateList = get2Weekdays(widget.selectedDate ?? now, 0);
  42. }
  43. });
  44. }
  45. }
  46. @override
  47. Widget build(BuildContext context) {
  48. return Column(
  49. mainAxisSize: MainAxisSize.min,
  50. children: [
  51. //顶部是固定的星期布局
  52. customDayOfWeek(),
  53. const SizedBox(height: 12),
  54. //底部是当前二周的数据
  55. DayTableView(
  56. weekdays: currentDateList,
  57. onSelect: (date) {
  58. setState(() {
  59. selectedDate = date;
  60. });
  61. //主动点击之后回调
  62. widget.onChangedSelectedDate?.call(date);
  63. },
  64. selectedDate: selectedDate ?? now,
  65. currentDate: now,
  66. )
  67. ],
  68. );
  69. }
  70. //星期的文本显示
  71. Widget customDayOfWeek() {
  72. final weekdays = getWeekdays(now, 0);
  73. return DayOfWeekView(weekdays: weekdays);
  74. }
  75. }