首页 > 解决方案 > sort 适用于 int,但不适用于 double

问题描述

如果 avgscore 包含 int 值,则该函数有效。但是,如果我将 avgscore 数组更改为 double 值,它就不起作用。我需要做哪些更改才能使其也对双精度值进行排序?

void main() {
      var ids = ['GEORGE', 'RUSTY', 'RIYAZAT', 'JAMES PAWNED'];
      var avgscore = [10, 13, 3, 40];
    
      final persons = List.generate(ids.length, (i) => Person(ids[i], avgscore[i]));
      print(persons); // [GEORGE = 10, RUSTY = 13, RIYAZAT = 3, JAMES PAWNED = 40]
    
      persons.sort((p1, p2) => p2.avgscore.compareTo(p1.avgscore));
    
      print(persons); // [JAMES PAWNED = 40, RUSTY = 13, GEORGE = 10, RIYAZAT = 3]
    
      // If you need to split the values into two arrays again
      ids = persons.map((p) => p.id).toList();
      avgscore = persons.map((p) => p.avgscore).toList();
    
      print(ids); // [JAMES PAWNED, RUSTY, GEORGE, RIYAZAT]
      print(avgscore); // [40, 13, 10, 3]
    }

错误信息是:

 Error: A value of type 'List<num>' can't be assigned to a variable of type 'double'.
 - 'List' is from 'dart:core'.
      double avgscore = [10.8, 13.7, 3.9, 10,7];

这是我将 int 值更改为 double 的时候。

标签: flutterdart

解决方案


我已经尝试了您的示例,并且效果很好。您在示例avgscore列表中有一个错误,最后一个值应该是 10.7(而不是 10,7)。我添加了Person类并使用了显式类型。看来你num avgscorePerson课堂上。

class Person{
  String id;
  double avgscore;
  
  Person(this.id, this.avgscore);
}
void main() {
      List<String> ids = ['GEORGE', 'RUSTY', 'RIYAZAT', 'JAMES PAWNED'];
      List<double> avgscore = [10.8, 13.7, 3.9, 10.7];
    
      final persons = List.generate(ids.length, (i) => Person(ids[i], avgscore[i]));
    
      persons.sort((p1, p2) => p2.avgscore.compareTo(p1.avgscore));
    
      // If you need to split the values into two arrays again
      ids = persons.map((p) => p.id).toList();
      avgscore = persons.map((p) => p.avgscore).toList();
    
      print(ids); // [RUSTY, GEORGE, JAMES PAWNED, RIYAZAT]
      print(avgscore); // [13.7, 10.8, 10.7, 3.9]
}

推荐阅读