Dart 如何在使用 Process.run 时隐藏 cmd?

Kir*_*ill 0 dart flutter

构建 Dart 应用程序后,函数 Process.run 开始打开一个可见的 cmd 一秒钟。

final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
  checkEnvironment ? 'powershell' : command,
  checkEnvironment ? [command] : args,
  runInShell: checkEnvironment,
);
Run Code Online (Sandbox Code Playgroud)

示例链接(gif):https : //imgur.com/jSPN6ew对于每个命令,它都会打开一个新的 cmd 窗口。

如果我使用idea(不是构建版本)启动应用程序 - 这样的事情不会发生

也试过这个版本 - 仍然是同样的问题:

final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
  'start',
   checkEnvironment ? ['/min', 'powershell', '-command', command] : ['/min', 'cmd', '/c', command],
   runInShell: true,
);
Run Code Online (Sandbox Code Playgroud)

发现一篇文章 runInShell 创建了一个新窗口,所以我删除了它,但结果仍然相同。

final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
  checkEnvironment ? 'powershell.exe' : 'cmd',
  checkEnvironment ? ['-command', command] : ['/c', command],
);
Run Code Online (Sandbox Code Playgroud)

Kir*_*ill 5

您可能已经在这里找到了解决方案:https : //github.com/flutter/flutter/issues/47891。但不要使用它!它不适用于窗口 7,并在关闭应用程序后用户无法删除应用程序时产生问题,因为一个 CMD 实例仍在运行。

试试这个方法

// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
  CreateAndAttachConsole();
} else {
  AllocConsole();
  ShowWindow(GetConsoleWindow(), SW_HIDE);
}
Run Code Online (Sandbox Code Playgroud)

您可以在 windows/runner/main.cpp 中替换它