I've just started learning dart. I saw that I can use '??' to give a value if entered value is null. But it isn't working as it should... I think.
This is my code:
import 'dart:io';
void main() {
print("Enter a string");
String input = stdin.readLineSync() ?? 'hello';
print(input);
}
If I'm not wrong this should print 'hello' if the user doesn't enter anything. But it just prints an empty line. I can't understand what the problem is.
The reason is that the readLineSync function returns null if no bytes preceded the end of input. Internally, the readLineSync function calls the readByteSync function. Which says:
"Synchronously reads a byte from stdin. This call will block until a byte is available. If at end of file, -1 is returned."
Since the input is read from stdin, you can trigger an EOF character by sending CTRL+Z (Windows) or CTRL+D (Linux) to your cmd/terminal, or by sending the characters to the stream itself (not sure how to do this in Dart).
When you press Enter, that inserts a CR/LF (depending on your OS) character into the input stream, which is then handled by the readLineSync method depending on its configuration and your current system.
Therefore, the return will not be null when you press enter. It will be the CR/LF character(s) if you set the retainNewlines parameter to true (which again, depends on your OS).
You can verify this by calling the following:
final value = stdin.readLineSync(retainNewlines: true); // press Enter/Return
print("read: ${value?.codeUnits.last}"); // prints 10 (LF) on Mac
Otherwise, it is false, and the actual return value of the function is will be determined by the encoding.decode method (defaults to systemEncoder). Either way, the encoding will be decoding an empty List<int> when you press Enter, and retainNewLines is false.
To account for all scenarios (null, CR/LF, value), you would write:
final input = stdin.readLineSync();
const CR = 13;
const LF = 10;
/// Handles different parameters that can be passed to readLinesSync
final value = switch (input) {
null || CR || LF => "Empty",
_ => input,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With