Search code examples
listflutterdartfold

Dart/Flutter: Method 'foldIndexed' isn't defined for the type 'List'


I am trying to use the foldIndexed() method on a List in Flutter/Dart, like so:

// should only compute the combined character length of the first two fruits
['apple', 'banana', 'cherry'].foldIndexed(
    0,
    (index, previousElement, element) =>
        index < 2 ? previousElement + element.length : previousElement);

For some reason it shows the following syntax error: The method 'foldIndexed' isn't defined for the type 'List'.

From this documentation I understand that foldIndexed() is part of Flutter and that it should be possible to use it on a List as List is an implementation of the Iterable abstract class.

Any ideas why Flutter casts the above mentioned error or won't let me use it? Or is there another way of getting access to the iteration index when using the fold() method on a List?


Solution

  • My problem was that I had forgotten to import collection.dart as pointed out by @pskink.