【问题标题】:The argument type 'Iterable<Future<SubwayStation>>' can't be assigned to the parameter type 'List<SubwayStation>'参数类型“Iterable<Future<SubwayStation>>”不能分配给参数类型“List<SubwayStation>”
【发布时间】:2021-07-10 16:00:08
【问题描述】:
class Stations extends ChangeNotifier {
  StationListState state = StationListState(loading: false, stations: []);

  Future<void> getMachedStations() async {
    state = state.copyWith(loading: true);
    notifyListeners();

    List<Map<String, dynamic>> aroundStations =
        await FindNearStation().getLocation();
    print(aroundStations.length);

    var subwaysRef = FirebaseFirestore.instance.collection('subways');


    var stations = aroundStations.map((searchedElement) async {
      String subwayStationName = yuk(searchedElement['subwayStationName']);

      try {
        print(' ::::: ${searchedElement['line']}');
        var lineRef = await subwaysRef
            .doc(searchedElement['line'])
            .collection(subwayStationName)
            .get();

        return SubwayStation.fromDoc(lineRef.docs[0]);
      } catch (e) {
        state = state.copyWith(loading: false);
      }
    });

    state = state.copyWith(loading: false, stations: stations); // <-- Error (stations : stations)
  }
}

我尝试获取返回的列表,但出现错误: 参数类型“Iterable”不能分配给参数类型“List”。

我该如何解决?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您将方法传递给map async,因此它返回Future 而不是您所期望的。您要么不使用map,要么等待每个Futures 完成。后者可能更容易,在您调用 copyWith 之前添加以下代码:

    var awaitedStations = await Future.wait(stations);
    

    完整代码:

    class Stations extends ChangeNotifier {
      StationListState state = StationListState(loading: false, stations: []);
    
      Future<void> getMachedStations() async {
        state = state.copyWith(loading: true);
        notifyListeners();
    
        List<Map<String, dynamic>> aroundStations =
            await FindNearStation().getLocation();
        print(aroundStations.length);
    
        var subwaysRef = FirebaseFirestore.instance.collection('subways');
    
    
        var stations = aroundStations.map((searchedElement) async {
          String subwayStationName = yuk(searchedElement['subwayStationName']);
    
          try {
            print(' ::::: ${searchedElement['line']}');
            var lineRef = await subwaysRef
                .doc(searchedElement['line'])
                .collection(subwayStationName)
                .get();
    
            return SubwayStation.fromDoc(lineRef.docs[0]);
          } catch (e) {
            state = state.copyWith(loading: false);
          }
        });
    
        var awaitedStations = await Future.wait<SubwayStation>(stations);    
    
        state = state.copyWith(loading: false, stations: awaitedStations);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2020-05-28
      • 2020-03-22
      • 1970-01-01
      • 2021-06-26
      • 2021-11-13
      • 2021-12-24
      • 2021-07-25
      • 2019-10-05
      相关资源
      最近更新 更多