Reputation: 1292
According to the readme for the Dart-Yaml pub package, I should be able to do the following:
var db = loadYamlDocument("db.yaml");
with print(db['hostname']);
giving me the value I have specified for port in that yaml, however I'm told that YamlDocument has no instance method []
. Okay, I guess that object doesn't have map behaviors, which is something I would have expected it to have. Looking through the docs, there's mention of a YamlMap, but I don't see how to implement that at all.
If I simply try print(db);
I actually get the string: 'db.yaml'
.
So I tried using new File('db.yaml');
and then sending that variable into the loadYamlDocument
method, but that doesn't work either.
Does anyone have any luck reading a yaml document and getting a map out of it in Dart?
Upvotes: 3
Views: 2741
Reputation: 5924
import "dart:io";
import "package:yaml/yaml.dart";
main() {
File file = new File('pubspec.yaml');
String yamlString = file.readAsStringSync();
Map yaml = loadYaml(yamlString);
}
EDIT:
Map loadYamlFileSync(String path) {
File file = new File(path);
if (file?.existsSync() == true) {
return loadYaml(file.readAsStringSync());
}
return null;
}
Future<Map> loadYamlFile(String path) async{
File file = new File(path);
if ((await file?.exists()) == true) {
String content = await file.readAsString();
return loadYaml(content);
}
return null;
}
main(List<String> args){
print(loadYamlFileSync("pubspec.yaml"));
}
Upvotes: 8
Reputation: 4013
Check the documentation pages for the Yaml package.
loadYamlDocument()
returns a YamlDocument
which is a 'heavyweight' class that gives you access to all the features of a Yaml document.
You probably want to use loadYaml
, which in most cases is going to return a Map
. The description says that the actual implementation of the map is a YamlMap
(the Yaml package's implementation of a Map
, that they presumably need to use instead of a HashMap
for some technical reason).
Upvotes: 3