+ isn't defined for the type 'Object

Issue

I keep getting this error => "The operator ‘+’ isn’t defined for the type ‘Object’. (view docs). Try defining the operator ‘+’."

How could I define it?

    import 'dart:math';

bool isArmstrongNumber(int number) {
    var numberString = number.toString();

return number ==
    numberString.split("").fold(0,
        (prev, curr) => prev! + pow(int.parse(curr), numberString.length));
}                             

main() {
  var result = isArmstrongNumber(153);
  print(result);
}

Solution

fold in Dart can have some problems when it comes to automatically determine what type it should return and handle. In these cases, we need to manually enter the type like this (fold<int>()):

import 'dart:math';

bool isArmstrongNumber(int number) {
  final numberString = number.toString();

  return number ==
      numberString.split("").fold<int>(
            0,
            (prev, curr) =>
                prev + pow(int.parse(curr), numberString.length).toInt(),
          );
}

void main() {
  final result = isArmstrongNumber(153);
  print(result); // true
}

I also fixed a problem where pow returns num which is a problem. In this case, we can safely just cast it to int without issues.

Details about this problem with fold

The problem here is that Dart tries to guess the generic of the fold based on the expected returned type of the method. Since the == operator expects an Object to compare against, fold will also expect to just return Object and the generic ends up being fold<Object>.

This is not a problem for the first parameter since int is an Object. But it becomes a problem with your second argument where you expect an int object and not Object since Object does not have the + operator.

Answered By – julemand101

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *