本文介绍了如何在 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.dart 传递给flutter 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 构建 apk
  • flutter build 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 不再有 Flavours,不再有 iOS Schemas.改变一切的命令参数

For more details see Flutter 1.17 no more Flavors, no more iOS Schemas. Command argument that changes everything

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 15:50
查看更多