Access to pubspec.yaml attributes (version) from Dart app

前端 未结 4 1775
孤街浪徒
孤街浪徒 2020-12-06 02:05

Is there any way to access some of the attributes listed in a pubspec.yaml file in that files Dart application?

In particular, the version and description attribute

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 02:26

    None of the above answers worked for me, but here's a working solution for a Flutter app:

    In your pubspec.yaml add the "pubspec.yaml" to assets:

    assets:
      - assets/
      - pubspec.yaml
    

    If you have a widget where you need to show the app version like this:

    ...
    Container(
      child: Text('Version: 1.0.0+1'),
    ),
    ...
    

    Wrap your widget with a FutureBuilder like this:

    import 'package:flutter/services.dart';
    import 'package:yaml/yaml.dart';
    
    ...
            FutureBuilder(
                future: rootBundle.loadString("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'
                    ),
                  );
                }),
    ...
    

    The services rootBundle property contains the resources that were packaged with the application when it was built.

    If you want to show the version without the build number, you can split the string like so:

    'Version: ${version.split("+")[0]}'
    

提交回复
热议问题