如何在应用程序内获取 Dart 和 Flutter 版本
2020-03-07
3694
如何在应用程序内
log()
Dart
和
Flutter
的版本?
例如:
String dartVersion = ?;
log("dart: $dartVersion");
2个回答
要执行 dart 版本,您可以使用 Platform 类直接返回 dart 版本,如本例所示:
import 'dart:io' show Platform;
var version = Platform.version;
print("version:"+version);
据我所知,没有直接的方法可以获取 flutter 版本,但您可以根据以下 CLI 命令创建自定义构建脚本以获取它:
flutter --version --machine
并使用其输出在构建时创建一个 dart 文件,我们可以将其导入到项目中。一旦到达那里,我们就可以在运行时直接读取它。
因此,我们将制作以下构建脚本来创建 dart 文件(名为 flutterVersion.dart):
rm lib/src/flutterVersion.dart # <-- prevents appending to an old file.
echo "Building flutterVersion.dart"
### the following creates a dart file, and appends the output of
### <flutter --version --machine> to a Map variable named "version",
### and finally appends a semicolon at the end.
echo "const Map<String,String> version = " >> lib/src/flutterVersion.dart
flutter --version --machine >> lib/src/flutterVersion.dart
echo ";" >> lib/src/flutterVersion.dart
echo "Continuing flutter build"
// put other build commands here.
这将创建以下文件:
const Map<String,String> version =
{
"frameworkVersion": "1.15.19-pre.9",
"channel": "master",
"repositoryUrl": "https://github.com/flutter/flutter.git",
"frameworkRevision": "e13e17009dcb009f12335eb281f7295ba42de771",
"frameworkCommitDate": "2020-03-06 21:38:35 -0800",
"engineRevision": "5aff3119480996ca014ec0f8d26d74db617b5852",
"dartSdkVersion": "2.8.0 (build 2.8.0-dev.12.0 9983424a3c)"
};
然后,您只需导入该文件并在运行时读取它:
import 'package:my_package/src/flutterVersion.dart';
main() {
print(version['channel']);
print(version['frameworkVersion']);
}
//output:
//master
//1.15.19-pre.9
William Terrill
2020-03-07
我将 William Terril 的解决方案改编为 dart 脚本。
import 'dart:io' show Process, ProcessResult;
import 'dart:convert' show json;
void main() {
Process.run('flutter', ['--version', '--machine']).then(
(ProcessResult results) {
final result = Map<String, Object>.from(
json.decode(results.stdout.toString()) as Map,
);
print(constantDeclarationsFromMap(result, 'kFlutter'));
},
);
}
String constantDeclarationsFromMap(Map<String, Object> map,
[String prefix = 'k']) {
String _capitalize(String text) =>
text.isEmpty ? text : "${text[0].toUpperCase()}${text.substring(1)}";
String _constantName(String name, String prefix) =>
prefix.isEmpty ? name : prefix + _capitalize(name);
return map.entries
.map((e) =>
'const ${_constantName(e.key, prefix)} = ${json.encode(e.value)};')
.join('\n');
}
然后运行类似
dart get_flutter_info.dart > flutter_info.dart
的程序,我将获得如下所示的文件:
const kFlutterChannel = "beta";
const kFlutterDartSdkVersion = "2.9.0 (build 2.9.0-21.10.beta)";
const kFlutterEngineRevision = "d6ee1499c27a156a797d9f1539ffb7892855c1d0";
const kFlutterFrameworkCommitDate = "2020-08-01 09:01:12 -0700";
const kFlutterFrameworkRevision = "916c3ac648aa0498a70f32b5fc4f6c51447628e3";
const kFlutterFrameworkVersion = "1.20.0";
const kFlutterRepositoryUrl = "https://github.com/flutter/flutter.git";
因此,您可以利用类型和自动完成功能。我希望有一种很好的方法将此代码注入构建过程。
Venkat D.
2020-08-14