Home > Software design >  How to sort/order a list by date in flutter or dart?
How to sort/order a list by date in flutter or dart?

Time:09-28

Widget _scheduleViewAllBody(ScheduleAll data) {
var viewAll = RectGetter(
  key: listViewKey,
  child: ListView.builder(
    controller: _scrollController,
    itemCount: data.data.length,
    itemBuilder: (context, index) {
      _keys[index] = RectGetter.createGlobalKey();

      String _month = DateTime.now().month.toString();
      if (DateTime.now().month < 10) {
        _month = '0'   DateTime.now().month.toString();
      }

      String _date = DateTime.now().day.toString();
      if (DateTime.now().day < 10) {
        _date = '0'   DateTime.now().day.toString();
      }

      if (_currentDate == null) {
        if (data.data[index].rawDate ==
            DateTime.now().year.toString()   '-'   _month   '-'   _date) {
          _currentDate = index;
        }
      }

      print(
          '${DateTime.now().year.toString()   '-'   DateTime.now().month.toString()   '-'   DateTime.now().day.toString()} => ${data.data[index].rawDate}');

CodePudding user response:

Not sure what you are trying to do in the code sample, especially with the DateTime.now()s, but the following example shows how you can easily sort a list of DateTimes:

void main() {
  final dates = [
    DateTime.utc(2001, 2, 2),
    DateTime.utc(2002, 1, 1),
    DateTime.utc(2000, 3, 3),
  ];
  dates.sort();
  print(dates);
}

CodePudding user response:

try this

 List<DateTime> datesList = [];
  datesList.sort(((a, b) => a.compareTo(b)));

with datesList containing all your DateTime

  • Related