Dart StringBuffer write()
Syntax & Examples


StringBuffer.write() method

The `write` method in Dart adds the contents of the specified object, converted to a string, to the buffer.


Syntax of StringBuffer.write()

The syntax of StringBuffer.write() method is:

 void write(Object obj) 

This write() method of StringBuffer adds the contents of obj, converted to a string, to the buffer.

Parameters

ParameterOptional/RequiredDescription

Return Type

StringBuffer.write() returns value of type void.



✐ Examples

1 Writing an integer to the buffer

In this example,

  1. We create a `StringBuffer` named `buffer`.
  2. We use the `write()` method to add the integer value 42 to the buffer.
  3. We convert the buffer to a string using `toString()` and print it to standard output.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer();
  buffer.write(42);
  print(buffer.toString());
}

Output

42

2 Writing a string to the buffer

In this example,

  1. We create a `StringBuffer` named `buffer`.
  2. We use the `write()` method to add the string 'Hello' to the buffer.
  3. We convert the buffer to a string using `toString()` and print it to standard output.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer();
  buffer.write('Hello');
  print(buffer.toString());
}

Output

Hello

3 Writing a list to the buffer

In this example,

  1. We create a `StringBuffer` named `buffer`.
  2. We use the `write()` method to add the list ['This', ' is', ' a', ' list'] to the buffer.
  3. We convert the buffer to a string using `toString()` and print it to standard output.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer();
  buffer.write(['This', ' is', ' a', ' list']);
  print(buffer.toString());
}

Output

[This,  is,  a,  list]

Summary

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