Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples
This tutorial explains how to read pubspec.yaml file in the example.
pubspec.yaml file contains the following things
name: dartapp
description: >-
dart example application.
version: 1.0.0
environment:
sdk: ">=2.10.0 <3.0.0"
dependencies:
ini: ^2.1.0
jiffy: ^5.0.0
quiver: 3.0.1+1
yaml: ^3.1.0
yaml_writer: 1.0.1
image: any
mime: any
path: any
package_info: any
dev_dependencies:
intl: any
How to read pubspec.yaml file in Dart
This tutorial is about reading the puspect.yaml file and print the content.
yaml package provides functions for reading yaml syntax files.
- Create a File object with pubspec.yaml
- read the file using
readAsString
, which returnsFuture<String>
with given yaml content. - Convert yaml String into Map using loadYaml function.
- Read the attributes from the map using the
Map[key]
syntax.
Here is an example program to read pubspec.yaml file
import 'package:yaml/yaml.dart';
import 'dart:io';
void main() {
File file = new File("pubspec.yaml");
file.readAsString().then((String content) {
Map yaml = loadYaml(content);
print(yaml['name']);
print(yaml['description']);
print(yaml['version']);
print(yaml['dependencies']);
print(yaml['dev_dependencies']);
});
}
Output:
dartapp
dart example application.
1.0.0
{ini: ^2.1.0, jiffy: ^5.0.0, quiver: 3.0.1+1, yaml: ^3.1.0, yaml_writer: 1.0.1, image: any, mime: any, path: any, package_info: any}
{intl: any}