0

I am building a list in flutter and need to sort it by date by showing the most recent timestamp first.

The list is created from a json like the one below:

[
   {
      "id":100,
      "timestamp":"2021-02-02T15:15:11Z",
      "name":"Entry1"
   },
   {
      "id":101,
      "timestamp":"2021-03-02T11:12:56Z",
      "name":"Entry2"
   }
]

Once the json is fetched with the fetchEntries function, I'd like to sort the list. This is my code:

class Values extends Object {
  int id;
  String timestamp;
  String name;

  Values(
      {this.id,
      this.timestamp,
      this.name});

  Values.fromJson(Map<String, dynamic> json) {
    id = json["id"];
    timestamp = json["timestamp"];
    name = json["name"];
  }
}
List<Values> _myList = [];
    fetchReport() {
        _timer = new Timer.periodic(Duration(seconds: 1), (timer) {
            fetchEntries(dates.id.toString(), dates.from, dates.to)
                .then((value) => {
                      _myList.addAll(value),
                      _postsController.add(1),
                      setState(() {})
                    });
            _timer.cancel();
        });
        //This is the sort code that doesn't work
        _myList.sort((a,b)=> a.timestamp.compareTo(b.timestamp));
      }

Alternatively, the list can be sorted by id in decreasing order but the timestamp method is preferred. Any suggestions how to do it properly?

2
  • You need to parse the timestamps before comparing them. Commented Apr 27, 2021 at 17:25
  • And why is timestamp a String? It should be a DateTime upon ingest, otherwise all users of Values will be independently needing to do the same calculation! Commented Apr 28, 2021 at 14:00

2 Answers 2

1

It is better to parse time after fetch data.

_myList.sort((a,b) {
    
    DateFormat formatter = DateFormat("yyyy-MM-ddTHH:mm:ssZ");
        DateTime aTime = formatter.parse(a["timestamp"]);
        DateTime bTime = formatter.parse(b["timestamp"]);
    
    return aTime.compareTo(bTime);
    //return bTime.compareTo(aTime);
    } 
Sign up to request clarification or add additional context in comments.

Comments

1

I think that issue why sorting does not work is that _myList.sort function is called before _myList is filled with data. The reason of that is that _myList is populated in future (when callback of fetchEntires(...).then) is called, while sort function is called right after timer is created (after Timer.periodic constructor).

In order to fix that you need to move _myList.sort to callback just after list is populated with data.

Regarding sorting itself.. While it should work comparing date in the format of your example, I would rather parse time to milliseconds and then compare those instead. Reason is that once you change date format to different one, like 'dd-MM-yyyy' sorting will be broken.

1 Comment

Thank you Alex for the hint, it turned out my sort function didn't parse the time string and I was doing the sort before being populated with data! Upvoted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.