关于在 class 之间传递参数的更好编程的 Dart 技巧

Dart tips for better programming about passing arguments between class

任何人都可以为我的下面的代码提供一些关于更好的 dart 编程的指导或提示吗? 能再简单点吗? 我认为这还不够好,我也有一个关于我在代码中添加的 'if statement' 构造的问题。

void main() {
  int month = 12;
  int day = 1;
  int year = 2022;
  int newDay;
  int newMonth;
  int newYear;
 
  Calculate calculate = Calculate(day,month,year);
  newDay = calculate.newDay;
   newMonth = calculate.newMonth;
   newYear = calculate.newYear;
  if (newMonth > 7) {
    newYear +=1;}
  print('New date is : $newDay / $newMonth / $newYear');
}

class Calculate{
  int month;
  int day;
  int year;
  
  Calculate(this.day, this.month, this.year);
  get newDay => day + 7;
  get newMonth => month + 1;
  get newYear => year + 1;
  
  
  //QUESTION.. how to construct below 'if statement' within this class?
  //if newMonth > 7 then newYear += 1;
  
}

我做了一些更改以删除 类,但我无法 return 该值,请帮助解决此问题:


void main() {
  int month = 12;
  int day = 1;
  int year = 2022;
  print(Calculate(day,month,year));

}

Calculate(day,month,year){
  int newday = 0;
  int newmonth = 0 ;
  int newyear = 0;
  newday = day + 7;
  newmonth = month + 1;
  newyear = year + 1;
  List<int> result;

  if (month > 3) {

    return  '$newday/$newmonth/$newyear';}
  else {return  '$newday/$newmonth/$newyear+1';}
    }

您应该用一个函数替换您的 Calculate class。这里不需要class。

不太明白你想做什么,但这里有一个小例子。您可以使用它并更改您的偏好。

void main() {
  DateData data = DateData(day: 5, month: 12, year: 2022);
  DateData newData = DateData(day: data.day, month: 8, year: 2022)
      .calculateYear()
      .calculateMonth()
      .calculateDay();

  print(data.toString());
  print(newData.toString());
}

class DateData {
  DateData({
    required this.day,
    required this.month,
    required this.year,
  });

  int day;
  int month;
  int year;

  @override
  String toString() => 'DateData(day: $day, month: $month, year: $year)';

  DateData calculateYear() {
    // Do something with `year` value.
    if (month > 7) {
      year += 1;
    }
    return this;
  }

  DateData calculateDay() {
    // Do something with `day` value.
    if (day > 31) {
      day = 1;
    }
    return this;
  }

  DateData calculateMonth() {
    // Do something with `month` value.
    if (month > 12) {
      month = 1;
    }
    return this;
  }
}