0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterデスクトップアプリでコマンドを起動する方法

Posted at

初めに

FlutterでWindowsのデスクトップアプリを作成するとき、コマンドプロンプトやPowerShellでコマンドを実行する場面があると思います。
本記事では、その方法をまとめました。

Flutterにデフォルトで含まれているdart:ioパッケージのProcess.runを使用します。

環境

  • 開発ツール: Visual Studio Code (VSCode)
  • Flutter バージョン: 3.24.3
  • OS: Windows 11以上
    ※Windows 10での動作は未確認です。

本題

前提として、すでにFlutterのProjectが作成されているものとします。

コマンドの実行例

Process.runを使ってコマンドを実行する簡単な例を以下に示します。

try {
    // 実行したいコマンド
    final result = await Process.run('cmd', ['/c', 'flutter --version']);
    
    // コマンドの実行結果を表示
    print('code: ${result.exitCode}');//実行結果の状態
    print('stdout: ${result.stdout}');//実行成功時に返ってくるテキスト
    print('stderr: ${result.stderr}');//実行失敗時に返ってくるテキスト
  } catch (e) {
    print('Error: $e');
  }

結果の確認

  • result.exitCode: 実行結果の終了コード(0が正常終了)
  • result.stdout: 実行成功時の出力
  • result.stderr: 実行失敗時のエラーメッセージ
    これらを利用して、結果に応じた機能を追加することができます。

PowerShellを使う場合

PowerShellを使用したい場合は、Process.runの第一引数にpowershellを指定します。以下はPowerShellを使用して特定のコマンドを実行する例です。

 try {
      // usbipd の状態を確認
      final result = await Process.run(
        'powershell',
        [
          'Start-Process',
          '-FilePath',
          'usbipd',
          '-ArgumentList',
          "'bind','--busid','$port','-f'",
          '-Verb',
          'RunAs'
        ],
        runInShell: true,
      );

      print('Exit Code: ${result.exitCode}');
      print('stderr: ${result.stderr}');
      print('stdout: ${result.stdout}');
.
.
.省略

上記の例では、選択したUSBデバイスをWSLに共有するためにusbipdコマンドを実行しています。

第二引数に入れる値は、https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.4
のStart-Processのやり方を参照してください。

最後に

すべてのコマンドが期待通りに動作するわけではありませんが、Windowsの機能をコマンドで操作できるのはとても便利です。

PowerShellについては完全に理解していない部分もあるため、良い資料があればぜひ教えていただけると嬉しいです。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?