month_calendar.dart 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import 'dart:html';
  2. import 'package:calendar_view/calendar_view/calendar_util.dart';
  3. import 'package:calendar_view/calendar_view/month_calendar/month_calendar_item.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'package:flutter/material.dart';
  6. class MonthCalendar extends StatefulWidget {
  7. const MonthCalendar({super.key});
  8. @override
  9. State<MonthCalendar> createState() => _MonthCalendarState();
  10. }
  11. class _MonthCalendarState extends State<MonthCalendar> {
  12. int currentYear = 2022; // 当前年份
  13. int currentMonth = 12; // 当前月份
  14. int selectedDayIndex = 0; // 当前选择的日期的下标,从0开始,范围是0-34 有时是 0-41
  15. int maxDaysLength = 35; // 最大的日期数组长度,有时是42
  16. List<DayStructure> daysList = []; // 当前维护的日期列表
  17. int _maxScheduleLines = 3; // 最大的日程行数【需要动态计算】
  18. double _viewHeight = 0; // 维护一个视口高度,如果视口高度不变,那么日程的高度不需要计算
  19. @override
  20. void initState() {
  21. super.initState();
  22. /// 获取当前时间判断年月
  23. final DateTime now = DateTime.now();
  24. currentYear = now.year;
  25. currentMonth = now.month;
  26. daysList = _countDaysList(currentYear, currentMonth);
  27. _selectToday();
  28. /// 虚拟的日程数据
  29. final List<DateTime> mockSchedule = [
  30. DateTime(2022, 12, 1),
  31. DateTime(2022, 12, 4),
  32. DateTime(2022, 12, 5),
  33. DateTime(2022, 12, 6),
  34. DateTime(2022, 12, 7),
  35. DateTime(2022, 12, 12),
  36. DateTime(2022, 12, 13),
  37. DateTime(2022, 12, 14),
  38. DateTime(2022, 12, 15),
  39. DateTime(2022, 12, 16),
  40. DateTime(2022, 12, 17),
  41. DateTime(2022, 12, 18),
  42. DateTime(2022, 12, 19),
  43. DateTime(2022, 12, 20),
  44. DateTime(2022, 12, 27),
  45. DateTime(2022, 12, 28),
  46. DateTime(2022, 12, 29),
  47. DateTime(2022, 12, 30),
  48. DateTime(2022, 12, 31),
  49. ];
  50. _setSchedule(mockSchedule);
  51. /// 监控resize事件,动态计算最大日程行数
  52. WidgetsBinding.instance.addPostFrameCallback((_) {
  53. _handleMaxScheduleLines();
  54. });
  55. /// web端监听resize事件
  56. if (kIsWeb) {
  57. window.onResize.listen((event) {
  58. WidgetsBinding.instance.addPostFrameCallback((_) {
  59. _handleMaxScheduleLines();
  60. });
  61. });
  62. }
  63. }
  64. @override
  65. Widget build(BuildContext context) {
  66. return Column(
  67. children: <Widget>[
  68. _buildMonthCalendarWeekTitle(),
  69. Expanded(child: _buildMonthCalendarDaysBody()),
  70. ],
  71. );
  72. }
  73. /// 构建「日、一、二、三、四、五、六」的标题
  74. Widget _buildMonthCalendarWeekTitle() {
  75. return Container(
  76. height: 30,
  77. child: Row(
  78. mainAxisAlignment: MainAxisAlignment.spaceAround,
  79. children: <Widget>[
  80. /// TODO[Gavin]: i18n
  81. _buildEachTitle('周日'),
  82. _buildEachTitle('周一'),
  83. _buildEachTitle('周二'),
  84. _buildEachTitle('周三'),
  85. _buildEachTitle('周四'),
  86. _buildEachTitle('周五'),
  87. _buildEachTitle('周六'),
  88. ],
  89. ),
  90. );
  91. }
  92. Widget _buildEachTitle(String title) {
  93. const weekTextStyle = TextStyle(fontSize: 12, color: Colors.black);
  94. return SizedBox(
  95. width: 25,
  96. child: Text(
  97. title,
  98. style: weekTextStyle,
  99. textAlign: TextAlign.center,
  100. ),
  101. );
  102. }
  103. /// 构建日历主体
  104. Widget _buildMonthCalendarDaysBody() {
  105. // 将35天分成5个周
  106. final weeksInMonth = <List<DayStructure>>[];
  107. for (var i = 0; i < daysList.length; i += 7) {
  108. weeksInMonth.add(daysList.sublist(i, i + 7));
  109. }
  110. return SizedBox(
  111. child: Column(
  112. mainAxisSize: MainAxisSize.max,
  113. mainAxisAlignment: MainAxisAlignment.spaceAround,
  114. children: weeksInMonth.map(_buildMonthCalendarDayRow).toList(),
  115. ),
  116. );
  117. }
  118. /// 构建每一行(周)
  119. Widget _buildMonthCalendarDayRow(List<DayStructure> sevenDays) {
  120. return Expanded(
  121. child: Container(
  122. child: Row(
  123. mainAxisAlignment: MainAxisAlignment.spaceAround,
  124. children: sevenDays.map(_buildEachDay).toList(),
  125. ),
  126. ),
  127. );
  128. }
  129. /// 构建每一天
  130. Widget _buildEachDay(DayStructure day) {
  131. return Expanded(
  132. child: Container(
  133. decoration: const BoxDecoration(
  134. border: Border(
  135. right: BorderSide(
  136. color: Colors.black12,
  137. width: 1,
  138. ),
  139. top: BorderSide(
  140. color: Colors.black12,
  141. width: 1,
  142. ),
  143. ),
  144. ),
  145. child: MonthDayItem(
  146. dayData: day,
  147. onSelect: (v) => _handleSelectedDayByIndex(v),
  148. maxScheduleLines: _maxScheduleLines,
  149. ),
  150. ),
  151. );
  152. }
  153. /// 传入起始年月,返回35个日期结构体
  154. List<DayStructure> _countDaysList(int year, int month) {
  155. maxDaysLength = _isNeedExtraRow(year, month) ? 42 : 35;
  156. final daysList = <DayStructure>[];
  157. final firstDay = DateTime(year, month, 1);
  158. final firstDayWeek = firstDay.weekday;
  159. final lastDay = DateTime(year, month + 1, 0);
  160. final lastDayOfMonth = lastDay.day;
  161. final lastDayOfLastMonth = DateTime(year, month, 0).day;
  162. final today = DateTime.now();
  163. /// 转换后的 firstDayWeek
  164. final firstDayWeekIndex = (firstDayWeek) % 7;
  165. int nextMonthDay = 1;
  166. // 上个月的日期
  167. for (var i = 0; i < firstDayWeekIndex; i++) {
  168. daysList.add(
  169. DayStructure(
  170. index: i,
  171. date: DateTime(
  172. year, month - 1, lastDayOfLastMonth - firstDayWeekIndex + i + 1),
  173. isCurrentMonth: false,
  174. ),
  175. );
  176. }
  177. // 当月的日期
  178. for (var i = 0;
  179. (i < lastDayOfMonth) && daysList.length < maxDaysLength;
  180. i++) {
  181. daysList.add(
  182. DayStructure(
  183. index: i + firstDayWeek,
  184. date: DateTime(year, month, i + 1),
  185. isToday:
  186. today.year == year && today.month == month && today.day == i + 1,
  187. ),
  188. );
  189. }
  190. while (daysList.length < maxDaysLength) {
  191. daysList.add(DayStructure(
  192. index: daysList.length,
  193. date: DateTime(month == 12 ? year + 1 : year,
  194. month == 12 ? 1 : month + 1, nextMonthDay),
  195. isCurrentMonth: false,
  196. ));
  197. nextMonthDay++;
  198. }
  199. return daysList;
  200. }
  201. /// 计算是否需要显示六行日期,一般为5行,但是有时候会有6行
  202. bool _isNeedExtraRow(int year, int month) {
  203. final firstDay = DateTime(year, month, 1);
  204. final firstDayWeek = firstDay.weekday;
  205. final lastDay = DateTime(year, month + 1, 0);
  206. final lastDayOfMonth = lastDay.day;
  207. /// 转换后的firstDayWeek,%7是因为DateTime的weekday是从周日开始的,而我们的日历是从周一开始的
  208. final firstDayWeekIndex = (firstDayWeek) % 7;
  209. return firstDayWeekIndex + lastDayOfMonth > 35;
  210. }
  211. /// 通过下标选中日期,下标从0开始,允许的范围是0-34,有时是 0-42
  212. void _handleSelectedDayByIndex(int index) {
  213. assert(index >= 0 && index < maxDaysLength,
  214. 'index must be in 0-$maxDaysLength');
  215. assert(daysList.length == maxDaysLength,
  216. 'daysList length must be maxDaysLength');
  217. for (var element in daysList) {
  218. if (element.index == index) {
  219. element.isSelected = true;
  220. } else {
  221. element.isSelected = false;
  222. }
  223. }
  224. selectedDayIndex = index;
  225. setState(() {});
  226. }
  227. /// 选中当月第一天
  228. void _selectFirstDay() {
  229. for (var element in daysList) {
  230. if (element.isCurrentMonth) {
  231. _handleSelectedDayByIndex(element.index);
  232. break;
  233. }
  234. }
  235. }
  236. /// 选中今天
  237. void _selectToday() {
  238. for (var element in daysList) {
  239. if (element.isToday) {
  240. _handleSelectedDayByIndex(element.index);
  241. break;
  242. }
  243. }
  244. }
  245. /// 给日期设置日程的值
  246. void _setSchedule(List<DateTime> scheduleList) {
  247. /// 如果scheduleList中存在daysList中的日期,则设置hasSchedule为true
  248. for (var element in scheduleList) {
  249. for (var day in daysList) {
  250. if (element.year == day.date.year &&
  251. element.month == day.date.month &&
  252. element.day == day.date.day) {
  253. day.hasSchedule = true;
  254. }
  255. }
  256. }
  257. }
  258. /// 上个月
  259. void _handleLastMonth() {
  260. if (currentMonth == 1) {
  261. currentMonth = 12;
  262. currentYear--;
  263. } else {
  264. currentMonth--;
  265. }
  266. daysList = _countDaysList(currentYear, currentMonth);
  267. _selectFirstDay();
  268. setState(() {});
  269. }
  270. /// 下个月
  271. void _handleNextMonth() {
  272. if (currentMonth == 12) {
  273. currentMonth = 1;
  274. currentYear++;
  275. } else {
  276. currentMonth++;
  277. }
  278. daysList = _countDaysList(currentYear, currentMonth);
  279. _selectFirstDay();
  280. setState(() {});
  281. }
  282. /// 动态计算日历格内的最大日程行数
  283. void _handleMaxScheduleLines() {
  284. final size = MediaQuery.of(context).size;
  285. if (size.height == _viewHeight) return;
  286. print('计算最大日程行数');
  287. _viewHeight = size.height;
  288. final gridRows = (maxDaysLength / 7).floor();
  289. final gridHeight = size.height - 100; // 100 是日历头部的高度
  290. final gridItemHeight = gridHeight / gridRows;
  291. final scheduleAreaHeight = gridItemHeight - 30; // 30 是日期的高度
  292. final maxLines = (scheduleAreaHeight / 20).floor();
  293. setState(() {
  294. _maxScheduleLines = maxLines;
  295. });
  296. }
  297. }