如何在Dart的SplayTreeMap中使用元组或自定义类型作为键?
背景
我希望创建一个键为元组、值为映射列表的SplayTreeMap,示例结构如下:
{ (1, 2023): [ { "id": 1, "name": "Bob" }, { "id": 2, "name": "Alice" }, ], (3, 2023): [ { "id": 3, "name": "Charlie" }, { "id": 4, "name": "Diana" }, ] }
我在Dart Pad中进行测试,编写了如下代码:
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>',推测元组未实现Comparable接口。
于是我尝试自定义MonthYear类,代码如下,但仍出现相同错误:
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; }
问题
有没有办法实现需求或类似效果?我并非一定要用元组,但它最初看起来是最佳选择。
补充说明
我使用SplayTreeMap是因为需要按键进行降序排序。
编辑:
我想到可以用DateTime作为键,但仍出现相同的类型错误。
最终解决方案
以下是我最终采用的代码:
import 'dart:collection'; void main() { var invoicesST = SplayTreeMap<DateTime, List>(); for(int i = 0; i < 10; i++) { var example = {'scId': 'sc$i', 'year': i + 2000, 'week': i, 'month': i}; invoicesST.update( DateTime(i+2000, i), (value) => [ ...(invoicesST[DateTime(i+2000, i)] ?? []), example ], ifAbsent: () => [example]); } print(invoicesST); }
这里使用DateTime作为键,此前的错误是因为使用方式不正确,同时也修正了update()的用法。
内容的提问来源于stack exchange,提问作者shmink
相关产品推荐
相关产品推荐

