Simple command-line app I/O in Dart

本小妞迷上赌 提交于 2019-12-11 02:42:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!