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

Miguel Ruivo picture Miguel Ruivo · Mar 5, 2019 · Viewed 7.6k times · Source

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.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Mar 5, 2019

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.