Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart User Input


Share

Dart User Input

A console program can ask the user to type something, like a name or a number.

To read what the user types, use stdin.readLineSync() from the dart:io library.

It waits until the user presses Enter, and then returns the line as a String.

Example

import 'dart:io';

void main() {
  print('What is your name?');
  String? name = stdin.readLineSync();
  print('Hello, $name');
}
Try it Yourself »

Result:

What is your name?
Hello, null

The result above is from a run where nobody typed anything.

That is why it says null.


Why Can the Input Be null?

The return type of readLineSync() is String?, a nullable string.

It returns null when there is no more input to read.

This happens when the program runs without a person typing, like in the run that made the result above.

If you run the program on your own computer with dart run, and type Anna, the result is:

Result:

What is your name?
Anna
Hello, Anna


Handle null With ??

A good program always handles the null case.

The if-null operator ?? gives a default value when the input is null:

Example

import 'dart:io';

void main() {
  print('What is your name?');
  String name = stdin.readLineSync() ?? 'Guest';
  print('Hello, $name');
}
Try it Yourself »

Result:

What is your name?
Hello, Guest

Now name is a normal String, and it is never null.

Use stdout.write() instead of print() if you want the user to type on the same line as the question:

Example

import 'dart:io';

void main() {
  stdout.write('Enter your city: ');
  String city = stdin.readLineSync() ?? 'Unknown';
  print('You live in $city');
}
Try it Yourself »

Result:

Enter your city: You live in Unknown

Since nobody typed anything here, the next output comes right after the question, on the same line.


Clean Up the Input

Users often type extra spaces by mistake.

Use trim() to remove spaces at the start and the end.

The ?. operator calls trim() only if the input is not null:

Example

import 'dart:io';

void main() {
  print('Pick a color:');
  String color = stdin.readLineSync()?.trim() ?? '';
  if (color.isEmpty) {
    print('You did not pick a color');
  } else {
    print('You picked $color');
  }
}
Try it Yourself »

Result:

Pick a color:
You did not pick a color

Read a Number

The input is always text, even when the user types a number.

To use it as a number, convert it with int.tryParse().

tryParse() returns null if the text is not a valid number, so the program does not crash when the user types abc:

Example

import 'dart:io';

void main() {
  print('How old are you?');
  String input = stdin.readLineSync() ?? '';
  int? age = int.tryParse(input);

  if (age == null) {
    print('That is not a valid age');
  } else {
    print('Next year you will be ${age + 1}');
  }
}
Try it Yourself »

Result:

How old are you?
That is not a valid age

If you run it on your own computer and type 30, the result is:

Result:

How old are you?
30
Next year you will be 31

This program reads lines until there is no more input, and adds up the numbers:

Example

import 'dart:io';

void main() {
  int total = 0;
  String? line = stdin.readLineSync();
  while (line != null) {
    total += int.tryParse(line) ?? 0;
    line = stdin.readLineSync();
  }
  print('Total: $total');
}
Try it Yourself »

Result:

Total: 0

Here there was no input at all, so the loop did not run and the total is 0.

Note: dart:io only works in programs that run on a computer or a server.

It does not work in Dart programs that run in a web browser.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.