userInput
In this example, we:
Import the
dart:io
library to access standard input (stdin
) and standard output (stdout
).Use
stdout.write
to display a prompt to the user.Use
stdin.readLineSync()
to read a line of input from the user.readLineSync()
reads the user's input as aString
. Note the use of!
to indicate that the result won't benull
.Finally, we print a greeting using the input provided.
Parsing User Input
Often, you'll want to parse user input into different data types like integers or doubles. Here's an example of parsing user input as an integer:
In this example:
We read user input as a string.
We use
int.tryParse()
to attempt to parse the input string as an integer. If parsing fails, we provide a default value of0
using the??
operator.We display the parsed value or an error message.
Handling User Input for Interactive Programs
For interactive programs or games, you can use libraries like dart:ffi
to create more sophisticated user interfaces.
Remember to handle user input carefully, validate it, and handle potential errors or exceptions to ensure the reliability of your Dart applications.
Last updated