【发布时间】:2022-01-19 15:35:24
【问题描述】:
我正在调用一个返回 XML 数据的 API
我有一个数据类来获取我需要的部分数据。
API 返回 instances 很好,但我无法提取数据列表,然后我需要调用一个函数(经过测试并且有效)来放置 map marker。
我需要从返回的列表vehicleactivity中取出lat, long并使用它
这是类
import 'package:xml/xml.dart';
class VehicleActivity {
VehicleActivity({
this.recordedAtTime,
this.itemIdentifier,
this.validUntilTime,
this.longitude,
this.latitude,
});
DateTime? recordedAtTime;
String? itemIdentifier;
DateTime? validUntilTime;
double? longitude;
double? latitude;
factory VehicleActivity.fromElement(XmlElement vaElement) => VehicleActivity(
recordedAtTime: DateTime.parse(
vaElement.findElements('RecordedAtTime').first.text,
),
itemIdentifier: vaElement.findElements('ItemIdentifier').first.text,
validUntilTime: DateTime.parse(
vaElement.findElements('ValidUntilTime').first.text,
),
longitude:
double.tryParse(vaElement.findAllElements('Longitude').first.text),
latitude:
double.tryParse(vaElement.findAllElements('Latitude').first.text),
);
}
我用这个 API fetch 调用它
Future <VehicleActivity?> fetchLiveLocations() async {
var client = http.Client();
VehicleActivity? vehicleActivity;
try{
var response = await client.get(Uri.parse(
'https_call'));
if (response.statusCode == 200) {
final doc = XmlDocument.parse(utf8.decode(response.bodyBytes));
final vehicleActivity = doc
.findAllElements('VehicleActivity')
.map((e) => VehicleActivity.fromElement(e))
.toList();
print(vehicleActivity);
}
} catch(e) {
print("Exception Happened: ${e.toString()}");
}
return vehicleActivity;
}
然后绘制我使用此功能的标记,这就是问题所在。
Future<void> showMapMarkers() async {
_unTiltMap();
var vehicleActivity = await fetchLiveLocations();
for (VehicleActivity vehicleActivity in vehicleActivity!) {
GeoCoordinates geoCoordinates = GeoCoordinates (vehicleActivity.latitude, vehicleActivity.latitude);
_addMapMarker(geoCoordinates, 1);
}
}
这就是问题
The type 'VehicleActivity' used in the 'for' loop must implement Iterable.
在这条线上
for (VehicleActivity vehicleActivity in vehicleActivity!) {
更新 - 绘图功能无法识别(我对我的 Json 使用 for 方法,这可能是问题,但已尝试其他选项)
Future<void> showMapMarkers() async {
_unTiltMap();
var vehicleActivity = await fetchLiveLocations();
for (VehicleActivity vehicleActivity in vehicleActivity!) {
GeoCoordinates geoCoordinates = GeoCoordinates (vehicleActivity.latitude, vehicleActivity.latitude);
_addMapMarker(geoCoordinates, 1);
}
}
【问题讨论】:
-
最终的 vehicleActivity = doc .findAllElements('VehicleActivity') .map((e) => VehicleActivity.fromElement(e)) .toList();打印(车辆活动);。 // 共享此打印的输出
-
已更新问题。我需要从列表
vehicleactivity中获取lat,long并放置标记。标记放置功能有效,它只是提取纬度,经度 -
将
Future <VehicleActivity?> fetchLiveLocations() async更改为Future List<<VehicleActivity>> fetchLiveLocations() async -
如果出现异常,您应该决定何时执行。你真的要像现在一样返回
null,还是抛出异常,还是返回<VehicleActivity>[](即空列表)