1. Create a List
You can create a list using the List
class or directly using the square brackets []
.
void main() {
// Step 1: Create a List of names
List<String> listOfNames = ["Alice", "Bob", "Charlie"];
print("Initial List: $listOfNames");
}
2. Append to List
To add an item to the list, use the .add()
method.
void main() {
List<String> listOfNames = ["Alice", "Bob", "Charlie"];
// Append a new name to the list
listOfNames.add("David");
print("After Append: $listOfNames");
}
Output:
After Append: [Alice, Bob, Charlie, David]
3. Remove a Specific Item
To remove an item, use the .remove()
method to remove by value or .removeAt()
to remove by index.
Remove by Value:
void main() {
List<String> listOfNames = ["Alice", "Bob", "Charlie", "David"];
// Remove specific name
listOfNames.remove("Charlie");
print("After Removing 'Charlie': $listOfNames");
}
Output:
After Removing 'Charlie': [Alice, Bob, David]
Remove by Index:
void main() {
List<String> listOfNames = ["Alice", "Bob", "Charlie", "David"];
// Remove by index
listOfNames.removeAt(1); // Removes "Bob" (index 1)
print("After Removing Index 1: $listOfNames");
}
Output:
After Removing Index 1: [Alice, Charlie, David]
4. Edit an Item in the List
To edit an item, directly access it using its index and assign a new value.
void main() {
List<String> listOfNames = ["Alice", "Bob", "Charlie"];
// Edit an item by index
listOfNames[1] = "Bobby"; // Update "Bob" to "Bobby"
print("After Edit: $listOfNames");
}
Output:
After Edit: [Alice, Bobby, Charlie]
5. Find an Item by Index
To find an item in the list by its index, access it using list[index]
.
void main() {
List<String> listOfNames = ["Alice", "Bob", "Charlie"];
// Find item by index
String itemAtIndex = listOfNames[2];
print("Item at Index 2: $itemAtIndex");
}
Output:
Item at Index 2: Charlie
Summary of Methods
Operation | Method | Example |
---|---|---|
Create a List |
|
|
Append an Item |
|
|
Remove by Value |
|
|
Remove by Index |
|
|
Edit an Item |
|
|
Find by Index |
|
|