Search code examples
flutterdartcalendar

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.


Solution

  • 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.