如何使用 Dart 从 for 循环中获取 return 值

How to return value from for loop using Dart

我在 Dart 中有以下 for 循环:

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

我的目标是遍历位置列表,这是我通过快照获取的,然后 return 每个值。不幸的是,Dart 分析器告诉我,这个函数没有以 return 语句结束。好吧,我不确定在这个例子中我做错了什么。

感谢任何帮助!

试试这个:

 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;
}

您不能在每个索引处 return 值,否则,该函数将仅在第一个索引处 return 编辑,而不会进行完整的迭代。相反,您应该 return 在循环外完成列表。

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;
}

我想你想要这样的东西

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

当我使用它时

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

控制台:

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