Add new element to list dart
In Dart, you can add a new element to a list using the add
method. Here's an example:
List<String> mylist = ['apple', 'banana', 'cherry'];
mylist.add('date');
print(mylist); // Output: [apple, banana, cherry, date]
Alternatively, you can use the addAll
method to add multiple elements to the list:
List<String> mylist = ['apple', 'banana', 'cherry'];
mylist.addAll(['date', 'elderberry', 'fig']);
print(mylist); // Output: [apple, banana, cherry, date, elderberry, fig]
You can also use the insert
method to add an element at a specific position in the list:
List<String> mylist = ['apple', 'banana', 'cherry'];
mylist.insert(1, 'date');
print(mylist); // Output: [apple, date, banana, cherry]
Note that the insert
method shifts all elements to the right of the insertion point to make room for the new element.
You can also use the addAt
method to add an element at a specific position in the list:
List<String> mylist = ['apple', 'banana', 'cherry'];
mylist.addAt(1, 'date');
print(mylist); // Output: [apple, date, banana, cherry]
Note that the addAt
method is only available in Dart 2.3 and later. In earlier versions of Dart, you can use the insert
method instead.