本文介绍了你如何在 Flutter/Dart 中将参数从命令行传递到 main?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何运行命令并使用 Flutter/Dart 传递一些自定义参数,以便可以在 main() 调用中访问它们,例如:

How would you run a command and pass some custom arguments with Flutter/Dart so they can then be accessed in the main() call such as:

flutter run -device [my custom arg]

这样我就可以访问它了:

So then I can access it with:

void main(List<String> args) {
  print(args.toString());
}

谢谢.

推荐答案

没有办法做到这一点,因为当您在设备上启动应用程序时,也不会传递任何参数.

There is no way to do that, because when you start an app on your device there are also no parameters that are passed.

如果这是为了开发,你可以通过 -t lib/my_alternate_main.dartflutter run 轻松切换不同设置
其中每个备用入口点文件使用不同的参数或不同的初始化全局变量调用相同的应用程序代码.

If this is for development, you can pass -t lib/my_alternate_main.dart toflutter run to easily switch between different settings
where each alternate entry-point file calls the same application code with different parameters or with differently initialized global variables.

更新

为了

  • 颤动运行
  • flutter build apk
  • flutter 构建 ios
  • 颤动驱动

为此添加了 --dart-define=... 命令行参数.

the --dart-define=... command line parameter was added for that purpose.

额外的键值对将作为来自 String.fromEnvironment、bool.fromEnvironment、int.fromEnvironment 和 double.fromEnvironment 构造函数的常量提供.

更多详情见Flutter 1.17 不再有 Flavors,不再有 iOS Schemas.改变一切的命令参数

const t = String.fromEnvironment("TEST");
flutter run --dart-define="TEST=from command line"

请注意 const 是必需的,并且变量名称区分大小写.

Be aware that const is required and that the variable name is case sensitive.

这篇关于你如何在 Flutter/Dart 中将参数从命令行传递到 main?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 19:32
查看更多