Home > Back-end >  Dart Fold method error - Summing a list int
Dart Fold method error - Summing a list int

Time:12-20

New to Dart.

I'm getting error summing a List using the .fold() method:

List<int> listInt = [1, 2, 3, 4, 5, 6];
int sumList = listInt.fold(0, (p, c) => p   c);

// First Print  
print(sumList);

// Second Pring
print(listInt.fold(0, (p, c) => p   c));

Printing sumList is perfectly fine, but when I print the same operation i get a compilation error:

The operator ' ' can't be unconditionally invoked because the receiver can be 'null'.

Any ideas why?

Thanks in advance.

CodePudding user response:

A case where the Dart type system is not smart enough to guess the correct type. What happens in your second line is that fold thinks you want a Object? returned so p becomes Object?.

In the first example, the Dart type system guesses the type based on the expected returned type which is int in your case. But because print expects Object?, you are really not getting the type you expect.

The reason is that the Dart type system does not really understand the concept of defining the returned type of a method given as second argument based on the type of the first argument. So fold is often problematic here if we don't have an typed output.

We can force it to understand what we want by changing your second line to:

print(listInt.fold<int>(0, (p, c) => p   c));

And it should work as you want.

  •  Tags:  
  • dart
  • Related