I want pass some arguments to Flutter main
function in main.dart
.
const customTestFlag = bool.fromEnvironment("CUSTOM_TEST_FLAG");
void main(List<String> args) {
// I want get some arguments in there
print('get args from main.dart => ${args.toString()}');
// or get arguments form environment
print('get args form env => $customTestFlag');
runApp(app.MyApp());
}
And I create flutter engine in Android like these:
List<String> dartVmArgs = new ArrayList<>();
dartVmArgs.add("--CUSTOM_TEST_FLAG=true");
dartVmArgs.add("--dart-define=CUSTOM_TEST_FLAG=true");
dartVmArgs.add("--dart-entrypoint-args=CUSTOM_TEST_FLAG=true");
dartVmArgs.add("--dart-entrypoint-args CUSTOM_TEST_FLAG=true");
FlutterEngine flutterEngine = new FlutterEngine(app, (String[]) dartVmArgs.toArray());
But these code not working for me,maybe launch app like flutter run --dart-define="CUSTOM_TEST_FLAG=true"
will work but this does not meet our needs, we expect to pass the value when Flutter engine is created or started
Thank you.
Create a global variable with const
keyword.
const test = String.fromEnvironment('test', defaultValue='defaultValue');
Then in main.dart file you can directly access test
variable easily.
While running app please use
flutter run --dart-define=test=yourDataHere
For more please refer to this link https://itnext.io/flutter-1-17-no-more-flavors-no-more-ios-schemas-command-argument-that-solves-everything-8b145ed4285d