How to take XML data from API and extract data list from it
To handle the issues in the comments:
- It should actually be returning a list (note the
toList()
) - It should return something (not null - at least for now) on exception or non-200
Rewrite this method as:
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>[];
}
}