Home > Software engineering >  How to make a List with months from current to previous etc.. Flutter/Dart
How to make a List with months from current to previous etc.. Flutter/Dart

Time:10-26

i can think how can you make a list with months from current'octomber' to previous etc etc, this list can have 12 months from now octomber 2022 to november 2021. not hardcoded, automated.

CodePudding user response:

You can use intl package like this:

List months = [];
for (var i = 0; i < 12; i  ) {
  var monthNumber = (DateTime.now().month - i);
  var monthDate = DateFormat.M().parse(
      (monthNumber < 1 ? 12 - (-monthNumber) : monthNumber).toString());
  var month = DateFormat.MMMM().format(monthDate);
  months.add(month);
}
print("months = $months");//months = [October, September, August, July, June, May, April, March, February, January, December, November]

if you get your list in Int try this:

List months = [];
for (var i = 0; i < 12; i  ) {
  var monthNumber = (DateTime.now().month - i);
  var month = (monthNumber < 1 ? 12 - (-monthNumber) : monthNumber);
  months.add(month);
}
print("months = $months");//months = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 12, 11]

CodePudding user response:

Here:

void main() {
  List<String> months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];
  
  DateTime now = DateTime.now();
    
  print(months);

  var result=(months
                ..addAll(months.getRange(0, now.month))
                ..removeRange(0,now.month)
             )
            .reversed.toList();
 
  
  
  print(result);
}
  • Related