Skip to main content

Introduction

In Dart, you can read user input from the console using the stdin object from the dart:io library. This is essential for creating interactive command-line applications.

Reading String Input

To read text input from the user, use stdin.readLineSync():
The return type is String? (nullable) because readLineSync() can return null if the input stream is closed or if an error occurs.

Reading Numeric Input

To read numeric values, you need to:
1

Read the input as a string

Use stdin.readLineSync() to get the user’s input
2

Parse the string to a number

Use int.parse() or double.parse() to convert the string to a number
3

Handle the nullable value

Use the ! operator to assert that the value is not null

Reading Integers

Complete Example

Here’s a complete program that demonstrates reading both string and numeric input:

Key Points

Import Required

Always import dart:io to access stdin

Nullable by Default

readLineSync() returns String? which must be handled

Parse Numbers

Use int.parse() or double.parse() for numeric input

Null Assertion

Use ! operator when you’re sure the input won’t be null

Best Practices

When using the ! operator, make sure the input won’t be null. Otherwise, your program will crash with a null reference error.
For more robust applications, consider using try-catch blocks when parsing numeric input to handle invalid input gracefully.