【发布时间】:2019-10-18 16:37:44
【问题描述】:
我是 Dart 的新手,并尝试使用答案 here 获得一个类来实现 List,并尝试使用文档 here 对这些对象的列表进行排序。为了发布 MWE,我删除了大部分代码:
import 'dart:collection';
class Transaction<E> extends ListBase<E>{
DateTime when;
Transaction(this.when);
List innerList = new List();
int get length => innerList.length;
void set length(int length){
innerList.length = length;
}
void operator[]=(int index, E value){
innerList[index] = value;
}
E operator [](int index) => innerList[index];
void add(E value) => innerList.add(value);
void addAll(Iterable<E> all) => innerList.addAll(all);
}
class Forecaster{
var transactions;
Forecaster(){
this.transactions = new List<dynamic>();
}
void tabulate(){
transactions.sort((a,b) => a.when.compareTo(b.when)); //problem line?
for(var d in transactions){
d.asMap().forEach((index,content){
int len = content.toStringAsFixed(2).length;
});
}
}
void forecast(var forWhen){
var first = new Transaction(DateTime.now());
first.addAll([5,9]);
transactions.add(first);
}
}
void main(){
Forecaster myTest = new Forecaster();
var dub = myTest;
dub..forecast(DateTime.now())
..tabulate();
}
使用问题行运行会导致异常(未捕获异常:TypeError: Closure 'Forecaster_tabulate_closure': type '(dynamic, dynamic) => dynamic' is not a subtype of type '(dynamic, dynamic) => int' ) 我不明白。如果我注释掉问题行,TypeError 就会消失。 TypeError 是不是因为我在定义 Transaction 时做错了什么?我正在尝试使用DartPad。
【问题讨论】:
标签: dart