2

I want to read different data from the console in a Dart server application, like:

forename : user inputs and enters
lastname : user inputs and enters
age : user inputs and enters

The following code works, but for 1 input item only:

var stream = new StringInputStream(stdin);
stream.onData = () {
    voornaam = stream.readLine();
};

But I can't get it to work for multiple items. Is there an easy way to do this in Dart ?

Thanks!

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

2 Answers2

1

Since you're using a StringInputStream rather than just a standard InputStream, and because you're looking to read text. Unless there's a particular reason, I would recommend using the onLine handler over the onData. On data will basically try to 'stream' the information in that it's called immediately not on a new line itself. Try something like the following (note, not complete code, missing proper error handling etc.)

#import('dart:io');

main() {
  var stream = new StringInputStream(stdin);
  stream.onLine = () {
    var str = stream.readLine().trim();
    print(str.toUpperCase());
    if(str == 'EXIT') exit(0);
  };
}

One other note to point out, if you ever are data-streaming and using the onData handler, it is recommended that you then use the read method, as opposed to the readLine method to retrieve your content, again due to the nature of onData not waiting for a full line of text to be received before being called.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Matt B
  • 6,192
  • 1
  • 20
  • 27
0
import 'dart:io';

void main() {
  print('-----welcome-----');
  print('what is your firstname');
  var fname = stdin.readLineSync();
  print('what is your lastname');
  var lname = stdin.readLineSync();
  print('what is your age');
  int age = int.parse(stdin.readLineSync());
  int left = 100 - age;
  print('your name is $fname $lname  and you are  $age years');
}
leens witts
  • 171
  • 1
  • 6