dart
Add item at first position of list dart
You can use List.insert() method to insert an item at 0 index of the list. We need to pass the index and the item as a parameter to the List.insert() method.
List<String> subjects = ["math", "physics", "chemistry"];
subjects.insert(0, "english");
print(subjects);
Output
["english", "math", "physics", "chemistry"]
In the above code, we have a list of named subjects that contains subject names. We want to add a new subject name to the first position of this dart list. We are using the below code syntax to insert the item at the beginning of the list.
subjects.insert(0, "english");
//Syntax
List.insert(index, item)
List<String> cars = ["Volvo", "TATA", "Hyundai"];
cars = ["Audi", ...cars];
print(cars);
// -> [Audi, Volvo, TATA, Hyundai]
You can use ... to add an item to the first position of a list using the Dart programming language. In the above code, we have a list named cars and we want to add a new car name to this list. We are adding them by assigning a new list to the cars list.
List<String> _fruits = ["Apple", "Banana", "Orange"];
_fruits = ["Papaya", for (String fruit in _fruits) fruit];
print(_fruits);
// -> [Papaya, Apple, Banana, Orange]
You can also use the above code to insert a new element at the beginning of a dart list.
Was this helpful?
Similar Posts
- Dart program for condition based item removal from a list
- Remove List item or element using its index in Dart
- Delete item from a List in Flutter [Dart]
- Get element position from the bottom of the screen
- Dart program to capitalize the first letter of a string
- Dart Program to add Single or Multiple Items to a List
- Dart Collections - Create a List or Array