如何使用逻辑在飞镖上标记每个日期?

How to label each date on dart using logic?

我正在尝试标记照片中显示的日期。第一个星期日过去后,标记的数字达到 20s。第2个星期日过去后,标记的数字达到30s。后面的数字代表星期几。例如。 25代表这个月的第二个星期五。

关于如何创建此逻辑有什么建议吗?

您可以使用 DateTime class 实现此目的。我添加了一个示例实现,您可以进一步优化它:

// Function that maps day with corresponding value
Map<int, int> generateMap(DateTime firstDateOfMonth) {
  final map       = <int, int>{};
  final numOfDays = getNumberOfDaysInMonth(firstDateOfMonth);
  int weekDay     = firstDateOfMonth.weekday;
  int sunday      = (7 - weekDay) + 1;
  int week        = 1;
  
  for (int i = 1; i <= numOfDays; i++) {
    if (sunday < i) {
      weekvv += 1;
      sunday += 7;
      weekDay = 1;
    }
    map[i] = (week * 10) + weekDay;
    weekDay++;
  }

  return map;
}

// Returns Number of days in a month
int getNumberOfDaysInMonth(DateTime date) {
  int numOfDays = 0;
  switch (date.month) {
    case DateTime.january:
    case DateTime.march:
    case DateTime.may:
    case DateTime.july:
    case DateTime.august:
    case DateTime.october:
    case DateTime.december:
      numOfDays = 31;
      break;
    case DateTime.april:
    case DateTime.june:
    case DateTime.september:
    case DateTime.november:
      numOfDays = 30;
      break;
    case DateTime.february:
      isLeapYear(date) ? 29 : 28;
      break;
  }
  return numOfDays;
}

// Checks whether the year is Leap Year
bool isLeapYear(DateTime date) => date.year % 4 == 0;

您可以通过月份的第一天来生成该特定月份的映射:

final now = DateTime.now();
final firstDayOfMonth = DateTime(now.year, now.month);

print(generateMap(firstDayOfMonth));

对于当前月份(2021 年 9 月),它打印出以下输出:

{
1: 13, 2: 14, 3: 15, 4: 16, 5: 17,
6: 21, 7: 22, 8: 23, 9: 24, 10: 25,
11: 26, 12: 27, 13: 31, 14: 32, 15: 33,
16: 34, 17: 35, 18: 36, 19: 37, 20: 41,
21: 42, 22: 43, 23: 44, 24: 45, 25: 46,
26: 47, 27: 51, 28: 52, 29: 53, 30: 54
}