Amir
Amir

Reputation: 441

Update object in List

I am calling a function in a Class which will update a List Object. I have successfully get the desired object and change the values in it. How do I update back the original list?

Here is my code:

void updateTask(
  Guid id, String title, String start, String end, String timeleft) {
  final taskToBeUpdated = _tasks.firstWhere((element) => element.id == id);
  taskToBeUpdated.title = title;
  taskToBeUpdated.start = start;
  taskToBeUpdated.end = end;
  taskToBeUpdated.timeLeft = timeleft;
}

I know I can use the forloop to achieve this

for (var i = 0; i < _tasks.length; i++) {
  if (_tasks[i].id == id) {
    _tasks[i].title = title;
    _tasks[i].start = start;
    _tasks[i].end = end;
    _tasks[i].timeLeft = timeleft;
  }
}

But is there a shorter way?

Upvotes: 2

Views: 1348

Answers (1)

VLXU
VLXU

Reputation: 729

Your first code should directly modify the object in the list since dart passes it by reference.

Try run this code to understand how this works:

List a = [{"dod":1}, {"dod":3}];

Map _b = a.firstWhere((e)=>e["dod"]==1);

_b["dod"] = 2;

print (a);

Upvotes: 5

Related Questions