Samuel Surya
Samuel Surya

Reputation: 455

Showing dynamic listview from XML in Flutter

I have XML like this:

<root>
   <customers>
      <customer customerId='A001'>
         <name>Alex</name>
         <address>...</address>
         <photo>http://myserver/images/alex.png</photo>
      <customer>
      <customer customerId='B001'>
         <name>Bruce</name>
         <address>...</address>
         <photo>http://myserver/images/bruce.png</photo>
      <customer>
      ...
   </customers>
</root>

And it is sent using http client.send like this routine:

await client.send(request).then((response)
    => response.stream.bytesToString()
    .then((value) {
      var xmlDoc = xml.parse(value);
      var _xmlList = xmlDoc.findAllElements("list").toList();
      ...
    })
  ).catchError((error) => print(error.toString()));

How can I convert the XML into the list array and showing the listview?

Thank you for your help.

Upvotes: 0

Views: 1816

Answers (1)

Richard Heap
Richard Heap

Reputation: 51732

Use the xml package. Start with an import like this:

import 'package:xml/xml.dart' as xml;

Decode the response as a string, then parse it and map it into whichever type of widget you want. I've just taken the simplest example of a Text. You might create your own composite widget with a card, details, image, etc.

  xml.XmlDocument document = xml.parse(response);
  List<Text> names = document
      .findAllElements('customer')
      .map<Text>((e) => Text(e.findElements('name').first.text))
      .toList();

Use the resulting list of widgets in a ListView as the children.

Upvotes: 4

Related Questions