flutter - 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 的时候。
解决方案
我已经尝试了您的示例,并且效果很好。您在示例avgscore
列表中有一个错误,最后一个值应该是 10.7(而不是 10,7)。我添加了Person
类并使用了显式类型。看来你num avgscore
在Person
课堂上。
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]
}
推荐阅读
- php - An Error Was Encountered The MongoDB PECL extension has not been installed or enabled in ubuntu codeigniter
- ios - 将十六进制代码转换为日期 (BLE) - 算法
- flutter - 什么是 Flutter 控制台?
- c# - 如何在linq中根据条件分组
- python - 我应该使用什么类型的数据库关系?
- java - 在服务器端获取 HTTPS 协议
- sql - 在 SQL Server 中获取小数点后指定长度的结果
- laravel - Laravel Passport - 在路由组中允许 auth:api 或 client_creds
- python - 在 pandas DataFrame 中查找最接近值的第一行的索引
- c++ - QWidget 监听其他 QWidgets 事件