MElochukwu
MElochukwu

Reputation: 51

How to generate list of years

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.

Upvotes: 1

Views: 1937

Answers (2)

Masum Billah Sanjid
Masum Billah Sanjid

Reputation: 1189

Try with this

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

Upvotes: 5

Mike4544
Mike4544

Reputation: 133

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.

Upvotes: 0

Related Questions