Dart Output
Dart Output (Print Text)
To show output in Dart, you use the print() function.
You put the value you want to show inside the parentheses:
Result:
Hello World
You can call print() as many times as you want.
Each call prints its value on a new line:
Example
void main() {
print('I am learning Dart.');
print('It is fun!');
print('Dart is used to build apps.');
}
Try it Yourself »
Result:
I am learning Dart.
It is fun!
Dart is used to build apps.
Print Numbers
You can also print numbers.
Numbers are written without quotes:
Result:
3
358
50000
You can do math inside print(), and Dart prints the result:
Result:
6
10
Print Several Values
print() takes exactly one value.
If you give it two values separated by a comma, the program does not run:
Result:
main.dart:2:8: Error: Too many positional arguments: 1 allowed, but 2 found.
Try removing the extra positional arguments.
print('Hello', 'World');
^
org-dartlang-sdk:///sdk/lib/core/print.dart:19:6: Context: Found this candidate, but the arguments don't match.
void print(Object? object) {
^^^^^
To print several pieces of text on one line, join them into one string with the + operator:
Result:
Hello World
To put a value inside a string, write a dollar sign $ and then the variable name, or write ${} around a calculation:
Example
void main() {
var name = 'Liam';
print('My name is $name');
print('5 + 3 is ${5 + 3}');
}
Try it Yourself »
Result:
My name is Liam
5 + 3 is 8
This is called string interpolation, and you will learn more about it in the String Interpolation chapter.
Print Without a New Line
print() always adds a new line after the value.
To print without a new line, use stdout.write().
stdout belongs to the dart:io library, so you must import it at the top of the file:
Example
import 'dart:io';
void main() {
stdout.write('Hello ');
stdout.write('World!');
stdout.write(' I am on the same line.');
}
Try it Yourself »
Result:
Hello World! I am on the same line.
To start a new line inside a string, use the special character \n:
Example
import 'dart:io';
void main() {
stdout.write('Apples\n');
stdout.write('Bananas\n');
print('Cherries\nOranges');
}
Try it Yourself »
Result:
Apples
Bananas
Cherries
Oranges
Note: In most programs, print() is all you need.
Use stdout.write() only when you want to build one line from several parts.