背景
我希望能够制作一个SplayTreeMap,键是元组,值是映射列表.它看起来如下所示:
{
(1, 2023): [
{
"id": 1,
"name": "Bob"
},
{
"id": 2,
"name": "Alice"
},
],
(3, 2023): [
{
"id": 3,
"name": "Charlie"
},
{
"id": 4,
"name": "Diana"
},
]
}
到目前为止,我只是在试验dart 垫,以确保我得到了正确的,我认为以下工作应该是有效的.
import 'dart:collection';
void main() {
var invoicesST = SplayTreeMap();
for(int i = 0; i < 10; i++) {
invoicesST[(i, i+2000)] = [];
invoicesST.update(
[(i, i+2000)],
(value) => [
...invoicesST[(i, i+2000)],
{
'scId': 'sc$i',
'year': i+2000,
'week': i,
'month': i
}
]);
invoicesST.update(
[(i, i+2000)],
(value) => [
...invoicesST[(i, i+2000)],
{
'scId': 'sc$i',
'year': i+2000,
'week': i+1,
'month': i
}
]);
}
print(invoicesST);
}
但输出是错误 TypeError: Record (0, 2000): type '(int, int)' is not a subtype of type 'Comparable<dynamic>'Error: TypeError: Record (0, 2000): type '(int, int)' is not a subtype of type 'Comparable<dynamic>'
.所以我猜记录不会延长到Comparable
年?
我认为我应该做自己的,并做了以下操作,但最终还是犯了同样的错误.
class MonthYear<T1, T2> {
final T1 month;
final T2 year;
MonthYear(this.month, this.year);
@override
bool operator ==(other) {
return (other is MonthYear)
&& other.month == month
&& other.year == year;
}
@override
int get hashCode => month.hashCode ^ year.hashCode;
}
问题
有没有办法让这件事奏效,或者至少有类似的办法?我不赞成使用Record类型,但它最初似乎是最好的.
边注
我使用SplayTreeMap
是因为我希望能够按降序对键进行排序.
EDIT:
我突然想到,我可以使用DateTime
作为关键字,但我的数据仍然是...is not a subtype of Comparable
最终结果
请阅读@jamesdlin的the marked solution,那里有这么多有用的信息.我想我应该添加我为保持一致性而确定的代码.
import 'dart:collection';
void main() {
var invoicesST = SplayTreeMap<DateTime, List>();
for(int i = 0; i < 10; i++) {
invoicesST[DateTime(i+2000, i)] = [];
invoicesST.update(
DateTime(i+2000, i),
(value) => [
...(invoicesST[DateTime(i+2000, i)] ?? []),
{'scId': 'sc$i', 'year': i + 2000, 'week': i, 'month': i}
]);
invoicesST.update(
DateTime(i+2000, i),
(value) => [
...(invoicesST[DateTime(i+2000, i)] ?? []),
{'scId': 'sc$i', 'year': i + 2000, 'week': i + 1, 'month': i}
]);
}
print(invoicesST);
}
DateTime
被用作密钥,但我不正确地使用它,就像EDIT中提到的那样,我使用update()
的方式也不正确.