Home > database >  Dart tips for better programming about passing arguments between class
Dart tips for better programming about passing arguments between class

Time:03-30

Can anyone give me some guidance or tips about better dart programming for my code below? Can it be more simpler? I think it's not good enough, and I also have a question about 'if statement' construction which i added inside the code.

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;
  
}

I make some changes to remove the classes, but i can't return the value, please help how to fix this :


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';}
    }

CodePudding user response:

Not really understand what you want to do, but here is a little example. You can play with it and change your preferences.

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;
  }
}

CodePudding user response:

You should replace your Calculate class with a function. There is no need for a class here.

  • Related