toString method

  1. @override
String toString()
override

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Implementation

@override
String toString() {
  String result = "";
  if (lunarYear != null) {
    int year = lunarYear!;
    if (year < 0) {
      //确保能读到正确的天干地支数据
      year++;
    }
    if (year < 1900) {
      //把远古年代转到近代来计算天干地支
      year += ((2018 - year) / 60).floor() * 60;
    }
    int absYear = lunarYear!.abs();
    String prefix = (lunarYear! < 0 ? "公元前" : "") + "$absYear";
    result += ((_tiangan[(year - 4) % _tiangan.length]) + (_dizhi[(year - 4) % _dizhi.length]) + "年($prefix)");
  }
  if (lunarMonth != null) {
    if (lunarMonth! < 1 || lunarMonth! > 12) {
      return "非法日期";
    }
    String month = _lunarMonthList[lunarMonth! - 1];
    String leap = isLeap ? "闰" : "";
    result += "$leap$month月";

    if (lunarDay != null) {
      if (lunarDay! < 1 || lunarDay! > 30) {
        return "非法日期";
      }
      result += _lunarDayList[lunarDay! - 1];
    }
  }
  return result.length < 1 ? "非法日期" : result;
}