flutter: Exception Happened: Bad state: No element in XML

Viewed 86

I have a working function to pull data from an XML API

I have added a parameter in the model to pull one extra number, so have based it on my other calls for a number data

PublishedLineName works well, and it is a number like DestinationRef. However, not every block in the List of data contains a DestinationRef, so when I call it comes back null like the .first builder says it will.

However, when I change it from .first.text to toString() it returns the data but with XML schema around it so is not a usable number.

How should I adapt

     vaElement.findAllElements('DestinationRef').first.text,

To be prepared for a null and carry on pulling the present data?

My model is here, and the error is on the highlighted line above. If I change it to a ('Ref') number that is present in each element of the list it returns fine.

...
    this.publishedLineName,
    this.destinationRef,

  String? publishedLineName;
  String? destinationRef;

        publishedLineName: 
            vaElement.findAllElements('PublishedLineName').first.text,
            
        destinationRef: 
            vaElement.findAllElements('DestinationRef').first.text,
...
1 Answers

You can see from here that findAllElements returns an Iterable.

Iterable.first throws if there are no elements.

So, you need to check if there are any elements found (i.e. whether a sub tag exists with that key in the XML document):

final elements = vaElement.findAllElements('DestinationRef');
return elements.isEmpty ? null /*or something else*/ : elements.first.text;

Put this in a re-usable method, as you'll use it often.

String? getFirstMatchingElement(XMLElement x, String key) {
  final elements = x.findAllElements(key);
  return elements.isEmpty ? null : elements.first.text;
}
Related