Reading YAML files in Flutter

Viewed 4229

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?

2 Answers

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.

If you need to get the value from pubspec.yaml before starting the application, then you need to:

  1. Add pubspec.yaml as an asset to pubspec.yaml from which you want to get the value.
  2. In the main method add WidgetsFlutterBinding.ensureInitialized().
  3. Add package yaml: ^3.1.0.
  4. Stop app and launch again.

main.dart

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:yaml/yaml.dart';

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await getAppVersion();
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(context) {
        return MaterialApp(home: HomePage());
      }
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(context) {
        return Scaffold();
      }
    }
    
    Future<void> getAppVersion() async {
      final yamlString = await rootBundle.loadString('pubspec.yaml');
      final parsedYaml = loadYaml(yamlString);
      print(parsedYaml['version']); // print 1.0.0+1
    }

pubspec.yaml

name: best_app
version: 1.0.0+1

environment:
  sdk: ">=2.16.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  yaml: ^3.1.0

flutter:
  assets:
    - pubspec.yaml # <-- add this 
Related