【问题标题】:How to take XML data from API and extract data list from it如何从 API 获取 XML 数据并从中提取数据列表
【发布时间】: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 &lt;VehicleActivity?&gt; fetchLiveLocations() async 更改为 Future List&lt;&lt;VehicleActivity&gt;&gt; fetchLiveLocations() async
  • 如果出现异常,您应该决定何时执行。你真的要像现在一样返回null,还是抛出异常,还是返回&lt;VehicleActivity&gt;[](即空列表)

标签: xml flutter dart


【解决方案1】:

处理 cmets 中的问题:

  1. 它实际上应该返回一个列表(注意toList()
  2. 它应该在异常或非 200 时返回一些东西(不为 null - 至少目前是这样)

将此方法改写为:

Future<List<VehicleActivity>> fetchLiveLocations() async {
  var client = http.Client();

  try {
    var response = await client.get(Uri.parse('https_call'));
    if (response.statusCode == 200) {
      final doc = XmlDocument.parse(utf8.decode(response.bodyBytes));
      return doc
          .findAllElements('VehicleActivity')
          .map((e) => VehicleActivity.fromElement(e))
          .toList();
    } else {
      // todo - fix later - for now return empty list
      return <VehicleActivity>[];
    }
  } catch (e) {
    print('Exception Happened: ${e.toString()}');
    // todo - fix later - for now return empty list
    return <VehicleActivity>[];
  }
}

【讨论】:

  • 绘制标记的功能(已在更新中突出显示)现在无法识别引发此错误的 vehicleActivity 类The argument type 'double?' can't be assigned to the parameter type 'double'. 我必须从 XML 调用中访问每个纬度、经度,然后使用我的方法绘制
  • longitudedouble?,因此可以为空。当您引用它时,请使用! 或可识别空值的运算符,例如myVehicleActivity.longitude ?? 0.0
  • 让它接受的唯一方法是使用Null Coalescing Operator (??)。主文件没有错误,但类不会接受它。这是前进的正确方向吗?如果是这样,我会想办法
  • 我是否需要在 API 调用中提取 Lat、Long ?
  • 我不知道最后一个问题是什么意思
猜你喜欢
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多