A2oz

How Do You Remove Data from an Array in Dart?

Published in Dart Programming 2 mins read

You can remove data from an array in Dart using various methods, depending on the specific element or elements you want to remove. Here are some common approaches:

1. Removing by Index:

  • Use the removeAt() method to remove the element at a specific index.
  • This method modifies the original array directly.

Example:

List<String> fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.removeAt(2); // Removes 'orange'
print(fruits); // Output: [apple, banana, grape]

2. Removing by Value:

  • Use the remove() method to remove the first occurrence of a specific value from the array.
  • This method modifies the original array directly.

Example:

List<String> fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.remove('banana');
print(fruits); // Output: [apple, orange, grape]

3. Removing All Occurrences of a Value:

  • Use the removeWhere() method to remove all elements that satisfy a given condition.
  • This method modifies the original array directly.

Example:

List<int> numbers = [1, 2, 3, 4, 5, 4, 3];
numbers.removeWhere((element) => element == 4);
print(numbers); // Output: [1, 2, 3, 5, 3]

4. Creating a New Array without Specific Elements:

  • Use the where() method to create a new array containing elements that satisfy a given condition.
  • This method does not modify the original array.

Example:

List<int> numbers = [1, 2, 3, 4, 5, 4, 3];
List<int> filteredNumbers = numbers.where((element) => element != 4).toList();
print(filteredNumbers); // Output: [1, 2, 3, 5, 3]

5. Removing Elements from a Specific Range:

  • Use the sublist() method to create a new array containing elements from a specific range.
  • This method does not modify the original array.

Example:

List<String> fruits = ['apple', 'banana', 'orange', 'grape'];
List<String> sublistFruits = fruits.sublist(1, 3); // Creates a new list with elements at index 1 and 2
print(sublistFruits); // Output: [banana, orange]

These are the most common ways to remove data from an array in Dart. Choose the method that best suits your specific needs.

Related Articles