The clear()
method in Dart removes all the items from a list and reduces its length to zero.
list_name.clear();
list_name
is the name of the list from which the items are removed.
The clear()
method takes no parameter.
This method does not return anything. Hence, its return type is void
.
The following code shows us how to use the clear()
method in Dart:
void main(){// Create list nameList name = ['John', 'Hamad', 'Maria', 'Rejoice', 'Elena'];// Display resultprint('The elements in the list: ${name}');// Returns list lengthprint('The list length:${name.length}');// remove items in the list// using clear()name.clear();// Returns list lengthprint('The list length:${name.length}');}
Note: If the list in question is a fixed-length list, then the method throws an “Unsupported operation: Cannot clear a fixed-length list” error and retains all the items within the list.