YAML

suggest change

YAML is a text format for configuration and structured data. Every Dart developer already uses it: pubspec.yaml, analysis_options.yaml and build.yaml are all YAML. It is also the format of GitHub Actions workflows, Docker Compose files, Kubernetes manifests and many application config files.

Dart has no YAML support in the SDK. The packages maintained by the Dart team are:

Package Use it for
yaml parsing YAML into Dart values, with source locations for error messages
yaml_edit writing YAML and editing existing files while keeping comments and formatting
pubspec_parse reading pubspec.yaml into typed objects
checked_yaml readable error messages when decoding YAML with json_serializable

The examples below were run with Dart 3.13, yaml 3.1.4, yaml_edit 2.2.4 and pubspec_parse 1.6.0.

Installing the packages

$ dart pub add yaml yaml_edit

This adds them to pubspec.yaml:

dependencies:
  yaml: ^3.1.3
  yaml_edit: ^2.2.2

Parsing YAML

loadYaml() parses a string and returns the value of the document. Mappings become YamlMap, sequences become YamlList, and scalars become ordinary Dart String, int, double, bool or null:

import 'package:yaml/yaml.dart';

const source = '''
# Server configuration
name: billing-service
port: 8080
debug: false
ratio: 0.75
owner: ~
tags: [api, payments]
database:
  host: db.internal
  pool: 10
''';

void main() {
  final doc = loadYaml(source);
  print(doc.runtimeType);
  print(doc['name']);
  print(doc['port'] + 1);
  print(doc['database']['host']);
  print(doc['tags'][1]);

  for (final MapEntry(:key, :value) in (doc as Map).entries) {
    print('$key: ${value.runtimeType}');
  }
}
$ dart run bin/main.dart
YamlMap
billing-service
8081
db.internal
payments
name: String
port: int
debug: bool
ratio: double
owner: Null
tags: YamlList
database: YamlMap

loadYaml() returns dynamic, so doc['port'] + 1 compiles without casts. That is handy for quick scripts, but a typo or a wrong type becomes a runtime error. For real programs, convert the result into typed objects as soon as possible (see below).

YamlMap implements Map and YamlList implements List, so the usual methods (entries, keys, length, where, map, ...) work on them. Comments are discarded by the parser.

How scalars are typed

YAML has no quotes requirement for strings, so the parser decides the type of each plain scalar by its text. package:yaml follows the YAML 1.2 core schema, which is stricter than the YAML 1.1 rules used by some other tools:

import 'package:yaml/yaml.dart';

const source = '''
a: yes
b: True
c: 0x1F
d: 0o17
e: 1e3
f: .inf
g: 2026-10-17
h: "8080"
i: 1_000
j: null
k: NO
l: 012
m: -.5
''';

void main() {
  final doc = loadYaml(source) as YamlMap;
  doc.forEach((key, value) {
    print('$key: ${value.toString().padRight(12)} ${value.runtimeType}');
  });
}
a: yes          String
b: true         bool
c: 31           int
d: 15           int
e: 1000.0       double
f: Infinity     double
g: 2026-10-17   String
h: 8080         String
i: 1_000        String
j: null         Null
k: NO           String
l: 12           int
m: -0.5         double

Things to notice:

YamlMap is read-only

The collections returned by loadYaml() are unmodifiable, and their static types are Map<dynamic, dynamic> and List<dynamic>, so they can't be cast to Map<String, dynamic>. When you need a regular mutable map, for example to apply overrides, convert it recursively:

import 'dart:convert';

import 'package:yaml/yaml.dart';

Object? toDart(Object? node) => switch (node) {
  YamlMap m => {for (final e in m.entries) e.key.toString(): toDart(e.value)},
  YamlList l => [for (final v in l) toDart(v)],
  _ => node,
};

void main() {
  final doc =
      loadYaml('''
name: demo
tags: [a, b]
limits: {cpu: 2, memory: 512}
''')
          as YamlMap;

  try {
    doc['name'] = 'changed';
  } on UnsupportedError catch (e) {
    print('UnsupportedError: ${e.message}');
  }

  try {
    final m = doc as Map<String, dynamic>;
    print(m);
  } on TypeError catch (e) {
    print(e);
  }

  final config = toDart(doc) as Map<String, Object?>;
  config['name'] = 'changed';
  (config['tags'] as List).add('c');
  print(config);
  print(config.runtimeType);

  print(const JsonEncoder.withIndent('  ').convert(doc));
}
UnsupportedError: Cannot modify an unmodifiable Map
type 'YamlMap' is not a subtype of type 'Map<String, dynamic>' in type cast
{name: changed, tags: [a, b, c], limits: {cpu: 2, memory: 512}}
_Map<String, Object?>
{
  "name": "demo",
  "tags": [
    "a",
    "b"
  ],
  "limits": {
    "cpu": 2,
    "memory": 512
  }
}

Map<String, dynamic>.from(doc) is not enough on its own, because it only copies the top level: nested values are still YamlMap and YamlList.

The last line shows that jsonEncode accepts YAML collections directly, which is the easiest way to turn YAML into JSON. Note that YAML allows non-string keys (1: one, [a, b]: x), which JSON doesn't; toDart above turns them into strings with toString().

Mapping YAML to typed classes

Dart 3 pattern matching is a compact way to check the shape of a document and pull out typed values in one step. Map patterns work on YamlMap because it is a Map:

import 'package:yaml/yaml.dart';

class DbConfig {
  final String host;
  final int port;
  final int pool;
  DbConfig({required this.host, required this.port, required this.pool});
}

class AppConfig {
  final String name;
  final int port;
  final List<String> tags;
  final DbConfig db;
  AppConfig({
    required this.name,
    required this.port,
    required this.tags,
    required this.db,
  });

  factory AppConfig.fromYaml(Object? yaml) {
    if (yaml case {
      'name': String name,
      'port': int port,
      'tags': List tags,
      'database': {'host': String host} && Map db,
    }) {
      return AppConfig(
        name: name,
        port: port,
        tags: tags.cast<String>().toList(),
        db: DbConfig(
          host: host,
          port: db['port'] as int? ?? 5432,
          pool: db['pool'] as int? ?? 5,
        ),
      );
    }
    throw FormatException('invalid config: $yaml');
  }

  @override
  String toString() =>
      'AppConfig($name, port: $port, tags: $tags, db: ${db.host}:${db.port} pool=${db.pool})';
}

void main() {
  final good = loadYaml('''
name: billing
port: 8080
tags: [api, payments]
database:
  host: db.internal
  pool: 20
''');
  print(AppConfig.fromYaml(good));

  final bad = loadYaml('''
name: billing
port: "8080"
tags: []
database: {host: db}
''');
  try {
    AppConfig.fromYaml(bad);
  } on FormatException catch (e) {
    print(e.message);
  }
}
AppConfig(billing, port: 8080, tags: [api, payments], db: db.internal:5432 pool=20)
invalid config: {name: billing, port: 8080, tags: [], database: {host: db}}

Optional keys with defaults (port, pool of the database) are read outside the pattern with as int? ?? default. A map pattern only checks the keys it lists, so extra keys in the file are ignored.

The weak spot is the error. The bad document has port: "8080" (a string), but the message doesn't say which value is wrong or where it is, and the printed map even hides the quotes. Config files are edited by people, so they deserve better errors.

Error messages that point at the file

Besides the values, the parser keeps a source span (file, line, column and the text) for every node. loadYamlNode() returns the root YamlNode, and YamlMap.nodes gives you child nodes instead of plain values. Throwing a YamlException with a node's span produces an error that shows the offending line:

import 'package:yaml/yaml.dart';

T field<T>(YamlMap map, String key) {
  final node = map.nodes[key];
  if (node == null) {
    throw YamlException('missing required key "$key"', map.span);
  }
  final value = node.value;
  if (value is! T) {
    throw YamlException(
      '"$key" must be $T, got ${value.runtimeType}',
      node.span,
    );
  }
  return value;
}

const source = '''
name: billing
port: "8080"
database:
  host: db.internal
''';

void main() {
  final root = loadYamlNode(source, sourceUrl: Uri.file('config.yaml'));
  final map = root as YamlMap;

  print(field<String>(map, 'name'));
  print('line of "database": ${map.nodes['database']!.span.start.line + 1}');

  for (final key in ['port', 'timeout']) {
    try {
      field<int>(map, key);
    } on YamlException catch (e) {
      print(e);
    }
  }
}
billing
line of "database": 4
Error on line 2, column 7 of config.yaml: "port" must be int, got String
  ╷
2 │ port: "8080"
  │       ^^^^^^
  ╵
Error on line 1, column 1 of config.yaml: missing required key "timeout"
  ╷
1 │ ┌ name: billing
2 │ │ port: "8080"
3 │ │ database:
4 │ └   host: db.internal
  ╵

Pass sourceUrl so messages name the file. Span lines and columns are zero-based, hence the + 1. Scalar nodes are YamlScalar, which also has a style property telling you whether the value was plain, quoted or a block scalar.

Syntax errors

Invalid YAML makes loadYaml() throw a YamlException (a FormatException subclass) with the same kind of span:

import 'package:yaml/yaml.dart';

void main() {
  const broken = '''
server:
  host: localhost
   port: 8080
''';
  try {
    loadYaml(broken, sourceUrl: Uri.file('broken.yaml'));
  } on YamlException catch (e) {
    print('message: ${e.message}');
    print('line: ${e.span!.start.line + 1}, column: ${e.span!.start.column + 1}');
    print(e);
  }

  try {
    loadYaml('a: 1\na: 2\n');
  } on YamlException catch (e) {
    print(e.message);
  }

  try {
    loadYaml('tags: [api, payments\n');
  } on YamlException catch (e) {
    print(e.message);
  }
}
message: Mapping values are not allowed here. Did you miss a colon earlier?
line: 3, column: 8
Error on line 3, column 8 of broken.yaml: Mapping values are not allowed here. Did you miss a colon earlier?
  ╷
3 │    port: 8080
  │        ^
  ╵
Duplicate mapping key.
While parsing a flow sequence, expected ',' or ']'.

Indentation errors like the extra space before port are the most common YAML mistake. Duplicate keys are an error too, rather than "last one wins" as in some parsers.

Multi-line strings, anchors and aliases

Block scalars are convenient for scripts and long text. | keeps newlines, > folds lines into one, and the +/- suffix keeps or strips trailing newlines. Anchors (&name) and aliases (*name) let you reuse a node:

import 'package:yaml/yaml.dart';

const source = r'''
defaults: &defaults
  adapter: postgres
  pool: 5

development:
  <<: *defaults
  database: dev_db

test:
  settings: *defaults
  database: test_db

script: |
  echo "building"
  dart compile exe bin/main.dart

summary: >
  This text is folded
  into a single line.

keep_trailing: |+
  two newlines follow

strip: |-
  no newline at the end
''';

void main() {
  final doc = loadYaml(source) as YamlMap;
  print(doc['development']);
  print(doc['test']);
  print(identical(doc['test']['settings'], doc['defaults']));
  print('script: ${doc['script'].toString().replaceAll('\n', r'\n')}');
  print('summary: ${doc['summary'].toString().replaceAll('\n', r'\n')}');
  print('keep: ${doc['keep_trailing'].toString().replaceAll('\n', r'\n')}');
  print('strip: ${doc['strip'].toString().replaceAll('\n', r'\n')}');
}
{<<: {adapter: postgres, pool: 5}, database: dev_db}
{settings: {adapter: postgres, pool: 5}, database: test_db}
true
script: echo "building"\ndart compile exe bin/main.dart\n
summary: This text is folded into a single line.\n
keep: two newlines follow\n\n
strip: no newline at the end

An alias refers to the same object as its anchor (identical returns true).

Look at development: the << merge key, common in Rails and Docker Compose files, is not supported by package:yaml. It is not part of YAML 1.2, so << is just an ordinary key. If your files rely on it, resolve merges yourself while converting to Dart maps:

import 'package:yaml/yaml.dart';

Object? toDartMerged(Object? node) {
  if (node is YamlList) return [for (final v in node) toDartMerged(v)];
  if (node is! YamlMap) return node;
  final result = <String, Object?>{};
  final merge = node['<<'];
  final bases = merge is YamlList ? merge : [if (merge != null) merge];
  for (final base in bases.reversed) {
    result.addAll(toDartMerged(base) as Map<String, Object?>);
  }
  for (final MapEntry(:key, :value) in node.entries) {
    if (key != '<<') result[key.toString()] = toDartMerged(value);
  }
  return result;
}

void main() {
  final doc = loadYaml('''
base: &base {adapter: postgres, pool: 5}
logging: &logging {log_level: info}
production:
  <<: [*base, *logging]
  pool: 50
''');
  print(toDartMerged(doc));
}
{base: {adapter: postgres, pool: 5}, logging: {log_level: info}, production: {log_level: info, adapter: postgres, pool: 50}}

Keys written in the map itself win over merged ones, and when several maps are merged the earlier ones win, as the merge key convention specifies.

Reading files and multiple documents

A YAML stream can hold several documents separated by ---, as Kubernetes manifests often do. loadYaml() rejects such input; use loadYamlStream() to get a YamlList with one value per document (or loadYamlDocuments() to get YamlDocument objects with their nodes):

import 'dart:io';

import 'package:yaml/yaml.dart';

Future<void> main() async {
  final file = File('k8s.yaml');
  await file.writeAsString('''
apiVersion: v1
kind: Service
metadata: {name: web}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: web}
spec: {replicas: 3}
---
# empty documents are allowed too
''');

  final text = await file.readAsString();
  final docs = loadYamlStream(text, sourceUrl: file.uri);
  print('documents: ${docs.length}');
  for (final doc in docs) {
    if (doc case {'kind': String kind, 'metadata': {'name': String name}}) {
      print('$kind/$name');
    } else {
      print('other: $doc');
    }
  }

  try {
    loadYaml(text);
  } on YamlException catch (e) {
    print(e.message);
  }
}
documents: 3
Service/web
Deployment/web
other: null
Only expected one document.

An empty document (or an empty file) loads as null, so check for that before treating the result as a map.

Writing YAML

package:yaml only reads. To produce YAML, use YamlEditor from yaml_edit: start from an empty document and set its root to a Dart value. It picks block style and quotes strings whenever the plain form would be read back as something else:

import 'package:yaml_edit/yaml_edit.dart';

void main() {
  final config = {
    'name': 'billing',
    'port': 8080,
    'debug': false,
    'version': '1.0',
    'empty': '',
    'tags': ['api', 'payments'],
    'database': {'host': 'db.internal', 'pool': 10},
    'motd': 'Hello\nWorld',
    'owner': null,
  };

  final editor = YamlEditor('')..update([], config);
  print(editor.toString());
}
name: billing
port: 8080
debug: false
version: "1.0"
empty: ""
tags:
  - api
  - payments
database:
  host: db.internal
  pool: 10
motd: "Hello\nWorld"
owner: null

version is quoted because 1.0 would come back as a double. The same trick converts JSON to YAML, and jsonEncode converts it back:

import 'dart:convert';

import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';

void main() {
  const json =
      '{"service":"web","replicas":3,"ports":[80,443],"labels":{"tier":"frontend"}}';

  final yamlText = (YamlEditor('')..update([], jsonDecode(json))).toString();
  print(yamlText);

  final back = jsonEncode(loadYaml(yamlText));
  print(back);
  print(back == json);
}
service: web
replicas: 3
ports:
  - 80
  - 443
labels:
  tier: frontend

{"service":"web","replicas":3,"ports":[80,443],"labels":{"tier":"frontend"}}
true

The values must be JSON-like: null, bool, num, String, List and Map. For your own classes, write a toJson()-style method that returns a map first.

Editing YAML and keeping comments

Loading a file, changing the map and writing it back would lose every comment and the original formatting. YamlEditor instead changes the text in place, touching only the parts that change. That makes it the right tool for programs that update files people also edit by hand, such as dart pub add (which uses it to edit pubspec.yaml):

import 'package:yaml_edit/yaml_edit.dart';

const original = '''
# Billing service config
name: billing
port: 8080   # public port
tags: [api, payments]
database:
  host: db.internal  # change per environment
  pool: 10
''';

void main() {
  final editor = YamlEditor(original);

  editor.update(['port'], 9090);
  editor.update(['database', 'pool'], 25);
  editor.update(['database', 'timeout'], 30);
  editor.appendToList(['tags'], 'internal');
  editor.update(['owner'], {'team': 'payments', 'email': 'pay@example.com'});

  print(editor.parseAt(['database', 'pool']).value);
  print(editor.edits.length);
  print('---');
  print(editor);
}
25
5
---
# Billing service config
name: billing
port: 9090   # public port
tags: [api, payments, internal]
database:
  host: db.internal  # change per environment
  pool: 25
  timeout: 30
owner:
  team: payments
  email: pay@example.com

A path is a list of map keys and list indexes. update replaces a value or adds a new key, and the existing style is kept: tags stays a flow list [...], new nested maps use block style. parseAt reads a node at a path, and edits lists the text changes made so far (useful to show a diff).

Lists and removals have their own methods:

import 'package:yaml_edit/yaml_edit.dart';

const original = '''
steps:
  - checkout
  - test
  - deploy
env:
  LOG_LEVEL: debug
  OLD_FLAG: "1"
''';

void main() {
  final editor = YamlEditor(original);

  final removed = editor.remove(['env', 'OLD_FLAG']);
  print('removed: ${removed.value}');

  editor.insertIntoList(['steps'], 1, 'lint');
  editor.spliceList(['steps'], 3, 1, ['build', 'deploy-staging']);
  editor.prependToList(['steps'], 'setup');
  print(editor);

  try {
    editor.update(['missing', 'key'], 1);
  } on ArgumentError catch (e) {
    print(e);
  }
}
removed: 1
steps:
  - setup
  - checkout
  - lint
  - test
  - build
  - deploy-staging
env:
  LOG_LEVEL: debug

Invalid path: (missing). Failed to traverse to subpath (missing)! Parent {steps: [setup, checkout, lint, test, build, deploy-staging], env: {LOG_LEVEL: debug}} does not contain key or index missing.

spliceList(path, index, deleteCount, values) works like JavaScript's splice: here it replaced deploy with two new steps. update can add one missing key at the end of a path, but not create intermediate maps: to add missing.key, first update(['missing'], {'key': 1}). A bad path throws a PathError, which is an ArgumentError.

To edit a file, read it into YamlEditor, make the changes and write editor.toString() back with File.writeAsString.

Reading pubspec.yaml

For pubspec.yaml there is no need to walk maps by hand: pubspec_parse (dart pub add pubspec_parse checked_yaml) parses it into a Pubspec object with typed dependencies and version constraints:

import 'dart:io';

import 'package:checked_yaml/checked_yaml.dart';
import 'package:pubspec_parse/pubspec_parse.dart';

void main() {
  final pubspec = Pubspec.parse(File('pubspec.yaml').readAsStringSync());
  print('${pubspec.name}, sdk: ${pubspec.environment['sdk']}');
  for (final MapEntry(:key, :value) in pubspec.dependencies.entries) {
    final version = switch (value) {
      HostedDependency(:final version) => version.toString(),
      GitDependency(:final url) => 'git $url',
      PathDependency(:final path) => 'path $path',
      _ => value.toString(),
    };
    print('  $key: $version');
  }

  try {
    Pubspec.parse('name: 42\n', sourceUrl: Uri.file('bad_pubspec.yaml'));
  } on ParsedYamlException catch (e) {
    print(e.formattedMessage);
  }
}
app, sdk: ^3.9.0
  checked_yaml: ^2.0.4
  pubspec_parse: ^1.6.0
  yaml: ^3.1.3
  yaml_edit: ^2.2.2
line 1, column 7 of bad_pubspec.yaml: Unsupported value for "name". type 'int' is not a subtype of type 'String' in type cast
  ╷
1 │ name: 42
  │       ^^
  ╵

ParsedYamlException comes from checked_yaml. The same package gives your own classes these located errors: generate fromJson with json_serializable using @JsonSerializable(checked: true) (see JSON) and decode with checkedYamlDecode(text, (map) => Config.fromJson(map!), sourceUrl: ...). It is the code-generation alternative to the hand-written field<T>() helper shown earlier.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents