Pass arguments into my application's main()
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.
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
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.
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.
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.