Why can't a general function performs a loop on any given list work

I wrote this function to perform a loop on any list

int loop(List list) {
  for (var i = 0; i < list.length; i++) {
    int currentValue = i;
    list[currentValue];
  }
}

but it says

The body might complete normally, causing 'null' to be returned, but the return type, 'int', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.

I added a throw statement but after a single loop the second time, it throws the exception. And I have no idea what to return outside the for-loop.

>Solution :

The body might complete normally, causing ‘null’ to be returned

Your method return type is int, means you need to return a int from the method.

int loop(List list) {
  for (var i = 0; i < list.length; i++) {
    int currentValue = i;
    list[currentValue];
  }
  return 0; //any int
}

Leave a Reply