Dart中的简单命令行应用程序I / O [英] Simple command-line app I/O in Dart

查看:266
本文介绍了Dart中的简单命令行应用程序I / O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法从用户取单个字符(整数)键盘输入并将它们存储到Dart命令行应用程序中的变量?我试过像:

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(););

尝试将键盘输入存储到变量choice但不能让它工作。

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.

推荐答案

目前你只能一次读取一行,

Currently you can only read a whole line at a time - i.e. once enter is pressed.

为此问题

更新:

readLine )函数等待用户的一行输入并将其作为字符串返回。

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;
}

这篇关于Dart中的简单命令行应用程序I / O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆