Dart エラー「Error: The operator + isn’t defined for the class Object」が発生した場合の対処法

Dart エラー「Error: The operator + isn’t defined for the class Object」が発生した場合の対処法

Dartで、エラー「Error: The operator ‘+’ isn’t defined for the class ‘Object’.」が発生した場合の対処法を記述してます。「fold」を型を指定せずに使用した際などに発生します。

環境

  • OS windows11 home
  • Dart 2.18.1

エラー全文

以下のコードを実行時に発生。

void main() {
  var list = [1, 2, 3, 4, 5];

  print(list.fold(0,(acc, element) => 
    (2 < element) ? acc * 2 : acc + element
  ));
}

エラー全文

main.dart:5:25: Error: The operator '*' isn't defined for the class 'Object'.
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '*' operator.
    (2 < element) ? acc * 2 : acc + element
                        ^
main.dart:5:35: Error: The operator '+' isn't defined for the class 'Object'.
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '+' operator.
    (2 < element) ? acc * 2 : acc + element

原因

「fold」使用時に、型を設定しないため

対処法

「型」を指定して実行します。

void main() {
  var list = [1, 2, 3, 4, 5];

  print(list.fold<int>(0,(acc, element) => 
    (2 < element) ? acc * 2 : acc + element
  )); // 24
}