Reputation: 3026
I am just creating a simple ToDo App in Flutter. I am managing all the todo tasks on the list. I want to add any new todo tasks at the beginning of the list. I am able to use this workaround kind of thing to achieve that. Is there any better way to do this?
void _addTodoInList(BuildContext context){
String val = _textFieldController.text;
final newTodo = {
"title": val,
"id": Uuid().v4(),
"done": false
};
final copiedTodos = List.from(_todos);
_todos.removeRange(0, _todos.length);
setState(() {
_todos.addAll([newTodo, ...copiedTodos]);
});
Navigator.pop(context);
}
Upvotes: 144
Views: 105698
Reputation: 4417
Adding a new item to the beginning and ending of the list:
List<String> myList = ["You", "Can", "Do", "It"];
myList.insert(0, "Sure"); // adding a new item to the beginning
// new list is: ["Sure", "You", "Can", "Do", "It"];
lastItemIndex = myList.length;
myList.insert(lastItemIndex, "Too"); // adding a new item to the ending
// new list is: ["You", "Can", "Do", "It", "Too"];
Upvotes: 11
Reputation: 1060
For those who are looking for an easy method to add multiple items at the start position you can use this reference:
List<int> _listOne = [4,5,6,7];
List<int> _listTwo = [1,2,3];
_listOne.insertAll(0, _listTwo);
Upvotes: 5
Reputation: 589
Better yet and in case you want to add more items :-
List<int> myList = <int>[1, 2, 3, 4, 5];
myList = <int>[-5, -4, -3, -2, -1, ...myList];
Upvotes: 4
Reputation: 371
The other answers are good, but now that Dart has something very similar to Python's list comprehension I'd like to note it.
// Given
List<int> list = [2, 3, 4];
list = [
1,
for (int item in list) item,
];
or
list = [
1,
...list,
];
results in [1, 2, 3, 4]
Upvotes: 7
Reputation: 825
I would like to add another way to attach element at the start of a list like this
var list=[1,2,3];
var a=0;
list=[a,...list];
print(list);
//prints [0, 1, 2, 3]
Upvotes: 17
Reputation: 267784
Use insert()
method of List
to add the item, here the index would be 0
to add it in the beginning. Example:
List<String> list = ["B", "C", "D"];
list.insert(0, "A"); // at index 0 we are adding A
// list now becomes ["A", "B", "C", "D"]
Upvotes: 284