MuTe33
MuTe33

Reputation: 122

How to return value from for loop using Dart

I have the following for loop in Dart:

 Locations allLocations(AsyncSnapshot<Results> snap) {
    for (var i = 0; i < snap.data.locationList.length; i++) {
      return snap.data.locationList[i];
    }
  }

My goal is to iterate through the list of locations, which I'm getting through a snapshot, and then return each value. Unfortunately, the Dart analyzer is telling me, that this function doesn't end with a return statement. Well, I'm not sure what I'm doing wrong in this example.

I appreciate any help!

Upvotes: 0

Views: 5117

Answers (3)

ibrahimkarahan
ibrahimkarahan

Reputation: 3015

I think u want something like this

Stream<int> allInts(List<int> list) async* {
    for (var i = 0; i < list.length; i++) {
      yield list.elementAt(i);
    }
  }

And when i use this

allInts(<int>[1, 3, 5, 7, 9]).listen((number) {
  print(number);
});

Console:

I/flutter (24597): 1
I/flutter (24597): 3
I/flutter (24597): 5
I/flutter (24597): 7
I/flutter (24597): 9

Upvotes: 1

Ravinder Kumar
Ravinder Kumar

Reputation: 7990

You must not return value at every index, otherwise, the function will be returned at first index only and will not go through complete iteration. Rather, you should return complete list outside loop.

List<Locations> mList= new List();
Locations allLocations(AsyncSnapshot<Results> snap) {
for(var i in  snap.data.locationList){
      mList.add(return snap.data.locationList[i]);
  }
return snap.data.locationList;
}

Upvotes: 0

Jay Gadariya
Jay Gadariya

Reputation: 1941

try this:

 Locations allLocations(AsyncSnapshot<Results> snap) {
  List returnedList = new List();
  for (var i = 0; i < snap.data.locationList.length; i++) {
    returnedList.add(snap.data.locationList[i]);
  }
  return returnedList;
}

Upvotes: 0

Related Questions