About the XML to Dart Converter
Flutter apps that talk to an older backend still meet XML, usually behind a small parsing layer that converts the document into maps. The classes that sit on top of those maps are pure boilerplate, and this generator writes them: one class per element shape, final fields with inferred types, a const constructor with required named parameters, and a matching pair of fromMap and toMap methods.
The serialisation code is written out rather than left as a comment, so nested types call each other properly. A nested element becomes Child.fromMap(map['child'] as Map<String, dynamic>), a repeated element becomes a mapped and materialised list, and a decimal value is read through as num before toDouble, which avoids the cast error that catches people out when a whole number arrives where a double was expected.
Sound null safety is respected in both directions. By default every field is non nullable and required in the constructor, matching a document where the sample shows every field. Tick the nullable option and each type gains a question mark while the required keywords disappear, which is the safer shape for a feed that omits fields. Class names come from the tags and plural container names are singularised, so a list of line elements produces a Line class. For a config file source, YAML to Dart starts from YAML instead.
How to use
- Paste an XML document that shows every field you want on the model.
- Leave Add fromMap and toMap on unless you only want the field declarations.
- Tick Make every field nullable if the source can omit fields.
- Copy the classes into
lib/modelsor download the.dartfile.
Common questions
- Does the generated code parse XML directly?
- No. Convert the document to a map first, with a package such as xml2json or your own DOM walk, then call fromMap.
- Why is a decimal read through num?
- A value like 8.0 can arrive as an int, and casting an int directly to double throws. Reading it as num then calling toDouble is safe either way.
- Are the classes immutable?
- Yes. Fields are final and the constructor is const, so instances can be used in const expressions and compared safely.
- Can it generate json_serializable annotations?
- No. It writes plain methods so the code works without build_runner or any code generation step.