Flutter获取Git信息插件git_info_plus的使用

Flutter获取Git信息插件git_info_plus的使用

pub package

从Flutter应用程序中获取Git信息。

screenshot-android screenshot-ios

使用方法

Dart
final String branchName = await GitInfo.branchName;
final DateTime lastCommitDate = await GitInfo.lastCommitDate;
final String lastCommitHash = await GitInfo.lastCommitHash;
final String lastCommitHashShort = await GitInfo.lastCommitHashShort;
final String lastCommitMessage = await GitInfo.lastCommitMessage;

设置

Android

你不需要进行任何设置。

iOS

为了在iOS上使用此库,你需要进行一些设置。

1. 在info.plist文件中添加值
Key Type Value
GitBranchName String undefined
GitCommitDate String undefined
GitCommitHash String undefined
GitCommitHashShort String undefined
GitCommitMessage String undefined

你可以复制并粘贴以下行:

<key>GitBranchName</key>
<string>undefined</string>
<key>GitCommitDate</key>
<string>undefined</string>
<key>GitCommitHash</key>
<string>undefined</string>
<key>GitCommitHashShort</key>
<string>undefined</string>
<key>GitCommitMessage</key>
<string>undefined</string>
setup-ios-1
2. 启用进程Info.plist文件

BuildSettings > Processes Info.plist File

改为YES

setup-ios-2
3-A. 添加运行脚本

BuildPhase >

添加一个新的运行脚本并粘贴以下内容:

plistBuddy="/usr/libexec/PlistBuddy"
infoPlistFile="${TEMP_DIR}/Preprocessed-Info.plist"

branchName=$(git branch --show-current)
commitDate=$(git --no-pager log -1 --format="%ai")
commitHash=$(git rev-parse HEAD)
commitHashShort=$(git rev-parse --short HEAD)
commitMessage=$(git log -1 --pretty=%s)

$plistBuddy -c "Set :GitBranchName $branchName" $infoPlistFile
$plistBuddy -c "Set :GitCommitDate $commitDate" $infoPlistFile
$plistBuddy -c "Set :GitCommitHash $commitHash" $infoPlistFile
$plistBuddy -c "Set :GitCommitHashShort $commitHashShort" $infoPlistFile
$plistBuddy -c "Set :GitCommitMessage $commitMessage" $infoPlistFile
setup-ios-3
3-B. 添加输入文件

${TEMP_DIR}/Preprocessed-Info.plist


完整示例Demo

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:git_info_plus/git_info_plus.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _branchName = 'Unknown';
  DateTime? _lastCommitDate;
  String _lastCommitHash = 'Unknown';
  String _lastCommitHashShort = 'Unknown';
  String _lastCommitMessage = 'Unknown';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    String branchName;
    DateTime? lastCommitDate;
    String lastCommitHash;
    String lastCommitHashShort;
    String lastCommitMessage;

    try {
      branchName = await GitInfo.branchName ?? 'Unknown';
    } catch (_) {
      branchName = 'Error';
    }
    try {
      lastCommitDate = await GitInfo.lastCommitDate;
    } catch (_) {
      // noop
    }
    try {
      lastCommitHash = await GitInfo.lastCommitHash ?? 'Unknown';
    } catch (_) {
      lastCommitHash = 'Error';
    }
    try {
      lastCommitHashShort = await GitInfo.lastCommitHashShort ?? 'Unknown';
    } catch (_) {
      lastCommitHashShort = 'Error';
    }
    try {
      lastCommitMessage = await GitInfo.lastCommitMessage ?? 'Unknown';
    } catch (_) {
      lastCommitMessage = 'Error';
    }

    if (!mounted) return;

    setState(() {
      _branchName = branchName;
      _lastCommitDate = lastCommitDate;
      _lastCommitHash = lastCommitHash;
      _lastCommitHashShort = lastCommitHashShort;
      _lastCommitMessage = lastCommitMessage;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('git_info插件示例'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              ListTile(
                title: const Text('分支名称'),
                subtitle: Text(_branchName),
                tileColor: Colors.white,
              ),
              const Divider(height: 1),
              ListTile(
                title: const Text('最后提交日期'),
                subtitle: Text(_lastCommitDate?.toString() ?? '未知'),
                tileColor: Colors.white,
              ),
              const Divider(height: 1),
              ListTile(
                title: const Text('最后提交哈希'),
                subtitle: Text(_lastCommitHash),
                tileColor: Colors.white,
              ),
              const Divider(height: 1),
              ListTile(
                title: const Text('最后提交哈希(短)'),
                subtitle: Text(_lastCommitHashShort),
                tileColor: Colors.white,
              ),
              const Divider(height: 1),
              ListTile(
                title: const Text('最后提交消息'),
                subtitle: Text(_lastCommitMessage),
                tileColor: Colors.white,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter获取Git信息插件git_info_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter获取Git信息插件git_info_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用git_info_plus插件来获取Git信息的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了git_info_plus依赖:

dependencies:
  flutter:
    sdk: flutter
  git_info_plus: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用git_info_plus插件:

  1. 导入包

    在你需要使用Git信息的Dart文件中导入git_info_plus包:

    import 'package:git_info_plus/git_info_plus.dart';
    
  2. 获取Git信息

    使用GitInfo()类来获取Git仓库的相关信息。以下是一个简单的示例,展示了如何获取和打印Git信息:

    import 'package:flutter/material.dart';
    import 'package:git_info_plus/git_info_plus.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      final GitInfo gitInfo = await GitInfo.fromCurrentDir();
    
      runApp(MyApp(gitInfo: gitInfo));
    }
    
    class MyApp extends StatelessWidget {
      final GitInfo gitInfo;
    
      MyApp({required this.gitInfo});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Git Info Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: Text('Git Info Demo'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('Branch: ${gitInfo?.branchName ?? "N/A"}'),
                  Text('Commit SHA: ${gitInfo?.commitSha ?? "N/A"}'),
                  Text('Commit Message: ${gitInfo?.commitMessage ?? "N/A"}'),
                  Text('Remote URL: ${gitInfo?.remoteUrl ?? "N/A"}'),
                ],
              ),
            ),
          ),
        );
      }
    }
    

在这个示例中,我们首先在main函数中异步获取Git信息,并将其传递给MyApp小部件。然后,在MyApp小部件中,我们使用Text小部件显示Git信息,如分支名称、提交SHA、提交消息和远程URL。

请注意,如果你的Flutter项目不是一个Git仓库,或者当前目录不是一个有效的Git仓库,GitInfo.fromCurrentDir()可能会抛出异常或返回null值。因此,在实际应用中,你可能需要添加一些错误处理逻辑来处理这些情况。

希望这个示例能帮助你更好地理解如何在Flutter项目中使用git_info_plus插件来获取Git信息。

回到顶部