Flutter/Dart program to sort number in a list in descending order

Issue

I am designing flutter app application that find the position of pupils through their total scores, I have used sort method but is not giving me a valid result.
”’List totals = [90, 50, 10, 5, 30, 9, 45];”’ my result if I use I sort method 10, 30, 45, 50, 5, 90, 9.
this is what I want to be my result / 5, 9, 10, 30, 45, 50, 90
please help me out

Solution

I think that your List is of type String, that’s why the order is different than comparing int. To fix this you parse the String to an int by using the parse method.

  List<String> totals = ["90", "50", "10", "5", "30", "9", "45"];
  totals.sort((a, b) => int.parse(a).compareTo(int.parse(b)));
  print(totals); // [5, 9, 10, 30, 45, 50, 90]

Answered By – quoci

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *