I want to have a Windows executable created with Flutter to be able to accept command arguments and print the result inside my CMD when I execute it like this :
commandtest.exe --type=csv
I wrote this code :
import 'dart:io';
import 'package:args/args.dart';
void main(List<String> args) {
var parser = ArgParser()..addOption("type", abbr: 't', defaultsTo: 'default');
try {
final ArgResults argResults = parser.parse(args);
final String type = argResults['type'] as String;
stdout.writeln('Type: $type'); // print() doesn't work either
exit(0);
} on Exception catch (e) {
stderr.writeln("error on parsing args : $e");
exit(1);
}
}
Here’s my expected behavior, in my CMD :
path/to/executable> mycommand.exe --type=csv
Type: csv
path/to/executable>
But for now, nothing works and my CMD is empty when i run my command :
path/to/executable> mycommand.exe --type=csv
path/to/executable>
However, I know it works because when I try my command like this :
mycommand.exe --type=csv > output.txt
the output.txt file is created and my result is correctly pushed inside.
I don’t see where’s the problem. Help please ?
2
Answers
The behaviour that you are showing occurs when you run a Windows GUI app from cmd: These do not print anything to the cmd output. They still have a stdout which you can redirect in the way that you showed – but they won’t print it to the console output.
You probably used
flutter create commandtest
to create your application. This way, you create a cmake project that builds an app as a windows gui application.Instead, use
dart create commandtest
to create a pure dart app. Copy your code tobincommandtest.dart
. Create the exe withdart compile exe bincommandtest.dart
.Summary
I would recommend making use of the commandline_or_gui_windows package on pub.dev. The package ensures that the console subsystem is used, so your stdout goes to the console. I modified the sample code from the commandline_or_gui_windows example to run your desired code, see the example below. Ensure to run the command after the package is imported, so that the Cpp code is modified before compilation. ref the readme for more details.
Command
flutter pub run commandline_or_gui_windows:create
Code
Testing
debug (-a is for flutter cmd)
flutter run -a --type -a "A cool type"
release (sub whatever your app name is commandline_or_gui_windows_example)
path: buildwindowsx64runnerRelease