Dart Tutorials

Dart List clear()
Syntax & Examples

Syntax of List.clear()

The syntax of List.clear() method is:

 void clear() 

This clear() method of List removes all objects from this list; the length of the list becomes zero.

Return Type

List.clear() returns value of type void.



✐ Examples

1 Clear a list of numbers

In this example,

  1. We create a list numbers containing integers [1, 2, 3].
  2. We use the clear() method to remove all elements from the list.
  3. The list becomes empty after clearing.
  4. We print the result to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3];
  numbers.clear();
  print(numbers); // Output: []
}

Output

[]

2 Clear a list of characters

In this example,

  1. We create a list characters containing characters ['a', 'b', 'c'].
  2. We use the clear() method to remove all elements from the list.
  3. The list becomes empty after clearing.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c'];
  characters.clear();
  print(characters); // Output: []
}

Output

[]

3 Clear a list of strings

In this example,

  1. We create a list words containing strings ['hello', 'world'].
  2. We use the clear() method to remove all elements from the list.
  3. The list becomes empty after clearing.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> words = ['hello', 'world'];
  words.clear();
  print(words); // Output: []
}

Output

[]

Summary

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