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);
}
Insert Using List. The List. insertAll( ) method is used to insert multiple elements at a particular index. This method also takes two arguments like List. insert( ), the first one is the index (must be int type value) and the second is the Iterable which contain the values to be added to the list.
For adding elements to a List , we can use add , addAll , insert , or insertAll . Those methods return void and they mutate the List object.
The syntax of declaring the list is given below. The Dart list is defined by storing all elements inside the square bracket ([]) and separated by commas (,). list1 - It is the list variable that refers to the list object. Index - Each element has its index number that tells the element position in the list.
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"]
Use
List.insert(index, value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With