Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass arguments from command line to main in Flutter/Dart?

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());
}

Thank you.

like image 207
Miguel Ruivo Avatar asked Mar 05 '19 13:03

Miguel Ruivo


4 Answers

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

If this is for development, you can pass -t lib/my_alternate_main.dart to flutter 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.

Update

For

  • flutter run
  • flutter build apk
  • flutter build ios
  • flutter drive

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

Additional key-value pairs that will be available as constants from the String.fromEnvironment, bool.fromEnvironment, int.fromEnvironment, and double.fromEnvironment constructors.

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

Example

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

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

like image 198
Günter Zöchbauer Avatar answered Nov 19 '22 02:11

Günter Zöchbauer


Android Studio

Adding command line arguments / environment variables to Android Studio Flutter project.


Edit

Run > Edit Configurations...

or click the Configuration drop-down selector

run/debug config selector

Add

Add your arguments in Additional arguments (quotes optional if no spaces) 2. Add a descriptive name if you like

Name and config arguments

Copy

Click copy button to easily add more config versions as needed

Duplicate config to add more

Select

Select your run Configs from drop down

Config Selector

Use

Using your arguments in code

e.g.

const String version = String.fromEnvironment('VERSION');

Use Arguments

like image 25
Baker Avatar answered Nov 19 '22 01:11

Baker


The arguments for the main method can be declared with the parameter --dart-entrypoint-args (short: -a), e.g.

flutter run -d linux --dart-entrypoint-args some_file.xml
like image 11
Janux Avatar answered Nov 19 '22 01:11

Janux


-dart-define is working in the stable channel version 1.17

from commandline

flutter run --dart-define=myVar="some value"

in for example main.dart:

const MY_VAR = String.fromEnvironment('myVar', defaultValue: 'SOME_DEFAULT_VALUE');
like image 6
Robin Manoli Avatar answered Nov 19 '22 03:11

Robin Manoli