在flutter应用程序中显示git上次提交哈希和当前分支/标签

cyt*_*nox 2 dart flutter

构建flutter应用程序时,如何访问源目录中的最后一个git提交哈希、当前分支和最后一个标签?我想在“关于版本”对话框中显示它。

https://pub.dev/packages/package_info但它没有关于 git 的信息。

是否有其他软件包可以提供此信息?

Rit*_*had 6

这可能不是最好的解决方案,但我是这样做的。

1. 将必要的文件添加到资产中

flutter:
  assets:
    - .git/HEAD         # This file points out the current branch of the project.
    - .git/ORIG_HEAD    # This file points to the commit id at origin (last commit id of the remote repository).
    - .git/refs/heads/  # This directory includes files for each branch which points to the last commit id (local repo).
Run Code Online (Sandbox Code Playgroud)

2. 从你的 .dart 代码中使用它

Future<String> getGitInfo() async {
  final _head = await rootBundle.loadString('.git/HEAD');
  final commitId = await rootBundle.loadString('.git/ORIG_HEAD');

  final branch = _head.split('/').last;

  print("Branch: $branch");
  print("Commit ID: $commitId");

  return "Branch: $branch,  Commit ID: $commitId";
}
Run Code Online (Sandbox Code Playgroud)

3. 如果需要,在你的 flutter 应用程序中显示它

FutureBuilder<String>(
  future: getGitInfo(),
  builder: (context, snapshot) {
    return Text(snapshot.data ?? "");
  },
)
Run Code Online (Sandbox Code Playgroud)

预期输出:

在此处输入图片说明

请注意,热重载也适用于 assets,因此它应该显示更改。

  • 这适用于 iOS,但不适用于 Android。可能是什么问题? (3认同)
  • @MohdShahid 请参阅[此](/sf/answers/4800654001/)答案以获取解决方案。 (3认同)