flutter如何获取pubspec.yaml中的配置内容?

码云
2020-11-17 09:10

当我们需要访问pubspec.yaml中配置属性的时候,我们可以通过两种方式:

1)将pubspec.yaml加到assets中,然后使用rootBundle读取,参考以下示例代码:

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

...
        FutureBuilder(
            future: rootBundle.loadString("pubspec.yaml"), //读取pubspec.yaml
            builder: (context, snapshot) {
              String version = "Unknown";
              if (snapshot.hasData) {
                var yaml = loadYaml(snapshot.data);
                version = yaml["version"]; //读取属性
              }

              return Container(
                child: Text(
                  'Version: $version'
                ),
              );
            }),

 

2)第二种方式,就是当作普通文件来读取,参考以下示例代码:

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

String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');

File f = new File(pathToYaml);
String yamlText =   f.readAsStringSync();
      Map yaml = loadYaml(yamlText);
      print(yaml['name']);
      print(yaml['description']);
      print(yaml['version']);
      print(yaml['author']);
      print(yaml['homepage']);
      print(yaml['dependencies']);
    });  

 

全部评论

相关文章