Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element at the beginning of the list in dart

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);
  }
like image 465
Ropali Munshi Avatar asked Aug 24 '19 07:08

Ropali Munshi


People also ask

How do you add elements to your first position in darts?

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.

How do you add an element to a list in darts?

For adding elements to a List , we can use add , addAll , insert , or insertAll . Those methods return void and they mutate the List object.

How do you declare a list variable in Dart?

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.


2 Answers

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"]
like image 156
CopsOnRoad Avatar answered Oct 27 '22 22:10

CopsOnRoad


Use

List.insert(index, value);
like image 21
Abdelrahman Lotfy Avatar answered Oct 27 '22 21:10

Abdelrahman Lotfy