下面代码表示累计求和。
main(){
Iterable<int> iterable = {1,3,5,7};//定义一个迭代器
//初始值为0,对当前和下一个求和,结果给result
int result= iterable.fold(0, (curr, next) => curr+next);
print(result);//输出
}
必须要指定result的数据类型,要不会出现如下的错误:
Error compiling to JavaScript: Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'. lib/main.dart:5:52: Error: The operator '+' isn't defined for the class 'Object?'. - 'Object' is from 'dart:core'. var result= iterable.fold(0, (curr, next) => curr+next); ^ Error: Compilation failed.