问题
Is there a way of taking single character (integer) keyboard inputs from the user and storing them to a variable in a Dart command-line app? I've tried something like:
Stream cmdLine = stdin
.transform(new StringDecoder())
.transform(new LineTransformer());
StreamSubscription cmdSubscription = cmdLine.listen(
(line) => (choice = line);
cmdSubscription.cancel(););
In an attempt to store a keyboard input into the variable 'choice' and many slight variations of this code but can't get it to work.
回答1:
Currently you can only read a whole line at a time - i.e. once enter is pressed.
Star this issue.
Updated:
The readLine() function waits for a line of input from a user and returns it as a string.
import 'dart:async';
import 'dart:io';
main() {
print('1 + 1 = ...');
readLine().then((line) {
print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
});
}
Future<String> readLine() {
var completer = new Completer<String>();
var input = stdin
.transform(new StringDecoder())
.transform(new LineTransformer());
var subs;
subs = input.listen((line) {
completer.complete(line);
subs.cancel();
});
return completer.future;
}
来源:https://stackoverflow.com/questions/16311876/simple-command-line-app-i-o-in-dart