Home > other >  How to generate list of years
How to generate list of years

Time:11-06

I am trying to generate lists of years from N year to the current year of the user. How can I automatically generate a list of years.

CodePudding user response:

Try with this

      int currentYear = DateTime.now().year;
      int startingYear = 2000;
      List yearList = List.generate((currentYear-startingYear) 1, (index) => startingYear index);

CodePudding user response:

You want to get the current year the user is in by using DateTime.now().year. After that you can have a loop that starts from the N year and stops when it reaches the current year.

The following is one way to do it:

List<int> getYears(int year) {
  int currentYear = DateTime.now().year;

  List<int> yearsTilPresent = [];

  while (year <= currentYear) {
    yearsTilPresent.add(year);
    year  ;
  }
  
  return yearsTilPresent;
}

You can read more about DateTime here.

  • Related