63

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?

newfurniturey
  • 37,556
  • 9
  • 94
  • 102

5 Answers5

95

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:

How can I print to stderr in Dart in a synchronous way?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
1

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
NirajPhutane
  • 1,586
  • 1
  • 12
  • 10
-1

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>");
Dharman
  • 30,962
  • 25
  • 85
  • 135
-1

Have a look are the dcli package you can use the echo function.

import 'package:dcli/dcli.dart';

void main() {
   echo("hi", newline: false);
}
Brett Sutton
  • 3,900
  • 2
  • 28
  • 53
-1

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));
}
Joao Victor
  • 509
  • 5
  • 10