flutter - 参数类型'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”。
我该如何解决?
解决方案
您将方法传递给map
async
,因此它返回 aFuture
而不是您期望的。您要么不使用map
,要么等待每个Future
s 完成。后者可能更容易在您调用之前添加以下代码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);
}
}
推荐阅读
- docker - 如何使用 docker 在 Windows 上运行 sqli-labs(一个 Web 应用程序)?
- python - 使用 flask_simpleldap 的 Flask 中的 LDAP 身份验证返回“凭据无效”
- python - 选择独立于正在使用的模型的特征的最佳方法是什么?
- c# - 插入 OracleClob 数组
- pkcs11interop - 在 PKCS11 互操作中更改 SO-Pin
- ios - 如何设置重复本地通知的开始和结束时间?
- vb.net - VB.NET 程序在 Windows 10 (system.net) 中停止工作
- sapui5 - MockServer:如何避免加载所有实体集?
- c++ - WaitForMultipleObjects() 访问被拒绝
- php - 如何在 php 中提取用户笔记本电脑/台式机模型