Dart StringBuffer writeln()
Syntax & Examples


StringBuffer.writeln() method

The `writeln` method in Dart converts an object to a string by invoking `Object.toString` and adds the result to `this`, followed by a newline.


Syntax of StringBuffer.writeln()

The syntax of StringBuffer.writeln() method is:

 void writeln([Object obj = "" ]) 

This writeln() method of StringBuffer converts obj to a String by invokingObject.toString and adds the result to this, followed by a newline.

Parameters

ParameterOptional/RequiredDescription
objoptionalthe object to convert to a string (default is an empty string)

Return Type

StringBuffer.writeln() returns value of type void.



✐ Examples

1 Write a message with writeln

In this example,

We create a string `message` with the value 'Hello, world!'. We create a `StringBuffer` named `buffer` and use the `writeln` method to write the message followed by a newline.

Dart Program

void main() {
  String message = 'Hello, world!';
  StringBuffer buffer = StringBuffer();
  buffer.writeln(message);
  print(buffer.toString());
}

Output

Hello, world!

2 Write an integer with writeln

In this example,

We create an integer `number` with the value 42. We create a `StringBuffer` named `buffer` and use the `writeln` method to write the number followed by a newline.

Dart Program

void main() {
  int number = 42;
  StringBuffer buffer = StringBuffer();
  buffer.writeln(number);
  print(buffer.toString());
}

Output

42

3 Write list of lines with writeln

In this example,

We create a list `lines` containing strings. We create a `StringBuffer` named `buffer` and use a loop to write each line from the list followed by a newline using the `writeln` method.

Dart Program

void main() {
  List<String> lines = ['Line 1', 'Line 2', 'Line 3'];
  StringBuffer buffer = StringBuffer();
  for (var line in lines) {
    buffer.writeln(line);
  }
  print(buffer.toString());
}

Output

Line 1
Line 2
Line 3

Summary

In this Dart tutorial, we learned about writeln() method of StringBuffer: the syntax and few working examples with output and detailed explanation for each example.