Reading YAML files in Flutter

Issue

the package yaml 2.2.1 helps Flutter users to read in YAML files. Unfortunately, the documentation is not enlightening me

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

main() {
  // load a YAML file
  var doc = loadYaml("YAML: YAML Ain't Markup Language");
  print(doc['YAML']);

  // Encode a YAML file
  print(json.encode(doc));
}

I put a YAML file in the folder

assets/yamlfiles/yamltoberead.yml

and wrote the necessary lines in the pubspec.yaml file.

I assume, I have to change the line "YAML: YAML Ain’t …" to the relative path of the yamltoberead.yml file, but it is throwing errors

type 'String' is not a subtype of type 'int' of 'index'

Is there another way to read in YAML files or how to fix the error?

Solution

Instead of changing the "YAML: YAML Ain't Markup Language" to the path to your yaml file,
first load a string version of the yaml file and then convert it to a map with the yaml package. This is an example (you will need to import flutter/services.dart):

import "package:flutter/services.dart" as s;
import "package:yaml/yaml.dart";

final data = await s.rootBundle.loadString('assets/yamlToRead.yaml');
final mapData = loadYaml(data);
print(mapData);

this will print a map containing your yaml data.

Answered By – Simonster

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.