Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Parse And Display XML Data In Flutter

Like JSON, XML can be utilized to get information from a web server. Notwithstanding, JSON is an information exchange design and just gives an information encoding determination, while XML is a language that utilizes severe semantics to indicate custom markup languages and gives much more than information trade.

This article will explore the Parse And Display XML Data In Flutter. We will see how to implement a demo program. We will show you how to parse and display XML data using the xml package in your flutter applications.

xml | Dart Package
Dart XML is a lightweight library for parsing, traversing, querying, transforming, and building XML documents. This…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

In general, JSON is quicker and more straightforward to utilize. All things considered, XML is all the more remarkable and can diminish programming risk in huge applications with rigid data structure prerequisites

To involve XML in Flutter, we really want to manage these means:

  • Get a XML record
  • Utilize the XML DOM to loop through the file
  • Extract values and store them in variables

We will show how to parse and display XML data in a flutter. It shows how XML data will work using the xml package in your flutter applications. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
xml: ^6.1.0

Step 2: Import

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

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main.dart file. We will create a new class XmlDataDemo. In this class, we will add the list that will be displayed in the ListView and the variable name was _students ie equal to the angle bracket.

List _students = [];

We will create a _xmlData() method. in this method, we will create a final dataList is equal to the angle bracket. This demo renders a list of students in a fiction school, including their student names and attendance. The information is provided in XML format.

void _xmlData() async {
final dataList = [];

const studentXml = '''<?xml version="1.0"?>
<students>
<student>
<studentName>Yash</studentName>
<attendance>95</attendance>
</student>
<student>
<studentName>Aditya</studentName>
<attendance>80</attendance>
</student>
<student>
<studentName>Rakhi</studentName>
<attendance>85</attendance>
</student>
<student>
<studentName>Mohit</studentName>
<attendance>75</attendance>
</student>
<student>
<studentName>Shaiq</studentName>
<attendance>70</attendance>
</student>
<student>
<studentName>Pragati</studentName>
<attendance>65</attendance>
</student>
</students>''';

}

Then, we will parse the date XML data and update the UI while using the setState() function. In this function, we will add _students is equal to the dataList and add all things in the _xmlData() method.

  final document = xml.XmlDocument.parse(studentXml);
final studentsNode = document.findElements('students').first;
final students = studentsNode.findElements('student');
for (final student in students) {
final studentName = student.findElements('studentName').first.text;
final attendance = student.findElements('attendance').first.text;
dataList.add({'studentName': studentName, 'attendance': attendance});
}

setState(() {
_students = dataList;
});

Now, we will create an initState() method. In this method, we will call the _xmlData() function when the app starts.

@override
void initState() {
super.initState();
_xmlData();
}

In the body, we will add the ListView.builder() widget. In this widget, we will add the itemBuilder is navigate to the Card widget. In the card widget, we will add a key, margin, color, and elevation. Its child, we will add the ListTile widget. In this widget, we will add the title and subtitle. Also, we will add itemCount was_students.length.

ListView.builder(
itemBuilder: (context, index) => Card(
key: ValueKey(_students[index]['studentName']),
margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 15),
color: Colors.teal.shade100,
elevation: 5,
child: ListTile(
title: Text(_students[index]['studentName']),
subtitle: Text("Attendance: ${_students[index]['attendance']}%"),
),
),
itemCount: _students.length,
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_xml_demo/splash_screen.dart';
import 'package:xml/xml.dart' as xml;

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Splash(),
);
}
}

class XmlDataDemo extends StatefulWidget {
const XmlDataDemo({Key? key}) : super(key: key);

@override
State<XmlDataDemo> createState() => _XmlDataDemoState();
}

class _XmlDataDemoState extends State<XmlDataDemo> {
List _students = [];

void _xmlData() async {
final dataList = [];

const studentXml = '''<?xml version="1.0"?>
<students>
<student>
<studentName>Yash</studentName>
<attendance>95</attendance>
</student>
<student>
<studentName>Aditya</studentName>
<attendance>80</attendance>
</student>
<student>
<studentName>Rakhi</studentName>
<attendance>85</attendance>
</student>
<student>
<studentName>Mohit</studentName>
<attendance>75</attendance>
</student>
<student>
<studentName>Shaiq</studentName>
<attendance>70</attendance>
</student>
<student>
<studentName>Pragati</studentName>
<attendance>65</attendance>
</student>
</students>''';

final document = xml.XmlDocument.parse(studentXml);
final studentsNode = document.findElements('students').first;
final students = studentsNode.findElements('student');
for (final student in students) {
final studentName = student.findElements('studentName').first.text;
final attendance = student.findElements('attendance').first.text;
dataList.add({'studentName': studentName, 'attendance': attendance});
}

// Update the UI
setState(() {
_students = dataList;
});
}

@override
void initState() {
super.initState();
_xmlData();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter XML Data Demo'),
centerTitle: true,
backgroundColor: Colors.cyan,
automaticallyImplyLeading: false,
),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: ListView.builder(
itemBuilder: (context, index) => Card(
key: ValueKey(_students[index]['studentName']),
margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 15),
color: Colors.teal.shade100,
elevation: 5,
child: ListTile(
title: Text(_students[index]['studentName']),
subtitle: Text("Attendance: ${_students[index]['attendance']}%"),
),
),
itemCount: _students.length,
),
),
);
}
}

Conclusion:

In the article, I have explained XML Data’s basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to XML Data On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Parse And Display XML Data in your flutter projectsWe will show you what the Introduction is. Make a demo program for working XML Data and you’ve learned how to parse and extract values from an XML document to present in a list view using the xml package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.