Skip to content
DeveloperMemos

Parsing YAML in Dart/Flutter

Dart, Flutter, YAML1 min read

YAML (short for “YAML Ain’t Markup Language”) is a human-readable data serialization format that is often used for configuration files and data exchange between systems. It has become increasingly popular due to its simplicity and readability compared to other formats like JSON or XML. If you are working with Dart or Flutter and need to parse YAML files, the yaml package provides an easy-to-use solution.

Installing the yaml package

To use the yaml package in your Dart or Flutter project, add it as a dependency in your pubspec.yaml file:

1dependencies:
2 yaml: ^3.1.1

Then run flutter pub get or dart pub get to install the package.

Parsing a YAML file

Once you have installed the yaml package, you can start parsing YAML files in your code. The loadYaml() function provided by the package converts a YAML string into a Dart object. For example, let’s say we have the following YAML file named config.yaml:

1name: John Doe
2age: 30
3isMarried: true

We can parse this file in our Dart code as follows:

1import 'package:yaml/yaml.dart';
2import 'dart:io';
3
4void main() {
5 final file = File('config.yaml');
6 final yamlString = file.readAsStringSync();
7 final doc = loadYaml(yamlString);
8
9 print(doc['name']); // John Doe
10 print(doc['age']); // 30
11 print(doc['isMarried']); // true
12}

In this example, we first read the contents of the config.yaml file into a string using the readAsStringSync() method provided by the dart:io library. Then we pass the YAML string to the loadYaml() function to convert it into a Dart object called doc. We can access the values in the doc object just like we would with any other Dart object.

Parsing a YAML list

If your YAML file contains a list, you can parse it as follows:

1- apple
2- banana
3- cherry

And the Dart code:

1import 'package:yaml/yaml.dart';
2import 'dart:io';
3
4void main() {
5 final file = File('fruits.yaml');
6 final yamlString = file.readAsStringSync();
7 final doc = loadYaml(yamlString);
8
9 final fruits = List<String>.from(doc);
10 print(fruits); // [apple, banana, cherry]
11}

In this example, we parse a YAML list containing three strings and convert it into a Dart list of type List<String>. The from() constructor is used to create a new list from the parsed YAML document.

Conclusion

Parsing YAML files in Dart/Flutter is easy with the yaml package. It provides a simple way to convert YAML strings or files into Dart objects, which can be easily manipulated and used in your code. With this knowledge, you can now use YAML as a configuration format for your Dart/Flutter projects.