How to sort a list of objects in Dart?

Asked

Viewed 1,773 times

1

Future<void> _getAllPesagens() async {
    List<Pesagem> pesagemFinal = List();
    await pesagemHelper.getAllPesagems().then((listaP) {
      print(listaP);
      if (listaP.isNotEmpty) {
        for (var peso in listaP) {
          if (peso.animalId == _caprinoSelecionado.idAnimal) {
            pesagemFinal.add(peso);
          }
        }
        setState(() {
          Comparator<Pesagem> pesagemComparator =
              (a, b) => b.data.compareTo(a.data);
          pesagemFinal.sort(pesagemComparator);
          pesagemFinal.forEach((Pesagem item) {
            print('${item.idPesagem} - ${item.data} - ${item.peso}');
          });
          pesos = pesagemFinal;
        });
      }
    });
  }

This is the code that takes from the database all the user-made Weighing, Weighing is an object that has the DATA attribute as String in the format of dd/mm/yyyy, I tried to use Commodore to sort the weighing list from the date, however the returned result was the following:

Ele ordena apenas parte da lista, o que não é o que eu queria

He orders only part of the list, which is not what I wanted

  • The problem with your ordering is that it was done with String. If you want to sort by dates the first thing you need is to convert the String date on a type DateTime and only then do the sort. There are several ways to do this conversion, just search "String to Datetime Dart" in google. Since your code is only one chunk, I won’t set up a functional example to illustrate. But basically it’s just that process you should do to fix.

  • Here solved, it was really worth !!

  • Have... I have inserted an answer so that it can serve as a guide for future consultations of community staff. Thus it can be marked as an accepted answer by indicating a path to follow. If possible, signal the accepted answer.

2 answers

2


The problem in your case is only the type of data you are using for sorting. In the current format that is encoded the order is correct by observing the type String which are common texts.

As you want to sort by date, what you need to do is first convert the dates of String for the format DateTime and the ordering you want can be done correctly.

0

You can also reverse the position of the comparators and convert to string, thus staying

//BEFORE (a, b) => b.data.compareTo(a.data);

//AFTERWARD (a, b) => a.data.toString.compareTo(b.data.toString); It will bring in the order of the oldest first(a, b) => b.data.toString.compareTo(a.data.toString); Will bring the latest first

Browser other questions tagged

You are not signed in. Login or sign up in order to post.