首页 > 解决方案 > 参数类型'Iterable>' 不能分配给参数类型 'List'

问题描述

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<Future>”分配给参数类型“List”。

我该如何解决?

标签: flutter

解决方案


您将方法传递给map async,因此它返回 aFuture而不是您期望的。您要么不使用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);
  }
}

推荐阅读