In Dart, I am using print()
to write content to the console.
Is it possible to use print()
without it automatically adding a newline to the output?
In Dart, I am using print()
to write content to the console.
Is it possible to use print()
without it automatically adding a newline to the output?
You can use stdout
:
import "dart:io";
stdout.write("foo");
will print foo
to the console but not place a \n
after it.
You can also use stderr
. See:
1. By using the dart io package
import 'dart:io';
void main() {
for(int r = 0; r < 5; r++){
for(int c = 0; c < r; c++){
stdout.write('Text ');
}
print('');
}
}
Output:
Text
Text Text
Text Text Text
Text Text Text Text
2. By using the direct print() method (Support to Dartpad)
void main() {
for(int r = 0; r < 5; r++){
print('Text ' * r);
}
}
Output:
Text
Text Text
Text Text Text
Text Text Text Text
Example for when multiplying by 0, 1, 2
void main() {
print('String' * 1);
print('String' * 0);
print('String' * 2);
}
Output:
String
StringString
You cannot customize the print() to prevent printing a newline in Dart (as in Python by using 'end' argument). To achieve this in Dart, use stdout.write() function, like
stdout.write("<your_message>");
Have a look are the dcli package you can use the echo function.
import 'package:dcli/dcli.dart';
void main() {
echo("hi", newline: false);
}
I encountered an issue while building an example in DartPad, and I came up with a solution that can handle various situations.
My solution involves creating a function that concatenates variables from a list and returns the resulting string.
Here's an example of how it works:
String buildManyInOneLine(List<dynamic> list) {
var newString = '';
for (var item in list) {
newString += '$item ';
}
return newString;
}
void main() {
var first = 'hey!';
var second = 'u r good?';
List<dynamic> listing = [first, second];
print(buildManyInOneLine(listing));
}