You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过VSCode的launch.json向Flutter平台主程序传命令行参数

给Flutter桌面应用传递命令行参数的解决方案

一、给Windows平台C++ main函数传递参数

你之前用args-to-main的配置是错误的,正确做法是在launch.json的配置项中添加对应平台的配置块,通过内部的args数组传递参数给C++主函数。修改后的配置如下:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "wideview",
            "request": "launch",
            "type": "dart",
            "flutterMode": "debug",
            "windows": {
                "args": ["--wait-for-debugger-attach"]
            }
        }
    ]
}

如果是macOS或Linux平台,只需把windows字段换成macos或linux即可,参数传递逻辑通用。

二、给Dart应用传递命令行参数

如果要给Flutter的Dart代码传参,有两种常用方式:

1. 通过launch.json配置传递

在配置项的根级别添加args数组,参数会直接传递给Dart的main函数:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "wideview",
            "request": "launch",
            "type": "dart",
            "flutterMode": "debug",
            "args": ["--env=production", "--user-id=123"]
        }
    ]
}

2. 通过命令行运行时传递

终端执行Flutter命令时直接追加参数:

# 方式1:用--dart-define定义环境变量式参数
flutter run --dart-define=ENV=production --dart-define=USER_ID=123

# 方式2:直接传递原始参数给Dart main
flutter run -- "arg1" "arg2"

3. 在Dart代码中获取参数

在Dart的main函数里,通过两种方式获取对应参数:

import 'dart:io';

void main(List<String> args) {
  // 获取直接传递的命令行参数
  print('Dart main 原始参数: $args');
  
  // 获取通过--dart-define定义的环境变量
  String? env = Platform.environment['ENV'];
  String? userId = Platform.environment['USER_ID'];
  print('环境变量参数 - ENV: $env, USER_ID: $userId');
}

内容的提问来源于stack exchange,提问作者Elad Maimoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:52:08