flutter-pi icon indicating copy to clipboard operation
flutter-pi copied to clipboard

Pass arguments into my application's main()

Open GoRadioGo opened this issue 4 years ago • 4 comments

Is there a way to get arguments into my main(), similar to below ? void main(List<String> arguments) async { print('args: $arguments'); // ... do my stuff ... }

I tried adding a "custom" command line option in the [flutter engine options] portion of the flutter-pi command line, but arguments was still an empty List.

GoRadioGo avatar Apr 09 '21 16:04 GoRadioGo

Yes you can, but it is a little tricky:

flutter-pi asset_dir param1 param2 

import 'dart:ffi';
import 'dart:io';

bool _isFutterPi = Platform.resolvedExecutable.endsWith('flutter-pi');

bool isFutterPiEnv() {
  return _isFutterPi;
}

var _flutterPiArgs = <String>[];

List<String> getFlutterPiArgs() {
  if (!isFutterPiEnv()) {
    return const <String>[];
  }
  if (_flutterPiArgs.isEmpty) {
    final dylib = DynamicLibrary.open('libc.so.6');
    var getpid =
        dylib.lookup<NativeFunction<_getpId>>('getpid').asFunction<_GetpId>();
    var cmd = File('/proc/${getpid()}/cmdline').readAsBytesSync();
    var index = 0;
    for (var i = 0; i < cmd.length; ++i) {
      if (cmd[i] == 0) {
        _flutterPiArgs
            .add(String.fromCharCodes(Uint8List.sublistView(cmd, index, i)));
        index = i + 1;
      }
    }
  }
  return List.unmodifiable(_flutterPiArgs);
}

Should return following list

  • flutter-pi
  • asset_dir
  • param1
  • param2

pezi avatar Apr 10 '21 05:04 pezi

I tried adding a "custom" command line option in the [flutter engine options] portion of the flutter-pi command line, but arguments was still an empty List.

Yeah the engine options are passed to the engine as-is, those are not the cmdline arguments for the main function of the Dart VM. I think @pezi's solution is a good way to do it. You could also use environment variables and fetch those using Platform.environment. I have no idea if its possible to pass arguments to main itself.

ardera avatar Apr 10 '21 10:04 ardera

Seems like flutter supports passing arguments to the app's main since 2.0. I'll add a way to pass arguments. Though not sure where to accept those arguments in the flutter-pi invocation.

ardera avatar Apr 14 '21 16:04 ardera

Great, I will follow that. I am still on 1.x, but hope to migrate to 2.x engine binaries next month. If not feasible, definitely a workaround along the lines of @pezi is always possible.

GoRadioGo avatar Apr 14 '21 16:04 GoRadioGo