Remove Item From Array In Dart
Code snippet for how to Remove Item From Array In Dart with sample and detail explanation
Removing an item from an array is a common programming task and Dart, as an object-oriented programming language, provides several methods to perform this operation. This article will guide you on how to remove an item from an array in the Dart programming language.
Code Snippet: Removing an Item from an Array in Dart
Below is the example of how to remove an item from an array in Dart:
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print(fruits);
fruits.remove('Banana');
print(fruits);
}
In this implementation, running the program will first print all items in the array and then, after removing ‘Banana’, it will print the updated array.
Code Explanation: Removing an Item from an Array in Dart
The main method in Dart is where the program execution starts. Inside this main method, we define a List (similar to an Array in other programming languages) of Strings named ‘fruits’. This ‘fruits’ list contains three string items: ‘Apple’, ‘Banana’, and ‘Cherry’. Printing the ‘fruits’ list will then print these items.
Next, the remove
method is used to remove an item from the ‘fruits’ list. The string ‘Banana’ is passed as an argument to this method which tells Dart to remove ‘Banana’ from the list. Once ‘Banana’ has been removed, printing the ‘fruits’ list will now print only ‘Apple’ and ‘Cherry’.
It’s worth noting that you need to make sure the item you want to remove is actually in the list. If you attempt to remove an item that does not exist in the list, Dart will not give an error but it will not modify the list either.
That’s pretty much it! This is how you can easily remove an item from an array or list in Dart. Remember to use the remove
method, and don’t forget to pass the item you want to remove as an argument to this method.