0

I am wondering whether I can create a function for my repository with which I can generically change any value within a variable which is based on a data class. Is this possible, how?

List<Task> tasks;

Future<void> changeTaskValue(int taskId, String variable, dynamic newValue) {
  task[taskId].<magic to get a reference to the variable> = newValue;
}

class Task {
  Task({this.taskId, this.taskName, this.status, });
  final int taskId;
  final String taskName;
  final String status;
}
...
void function abc() {
  changeTaskValue(taskId: 1, variable: 'taskName', newValue: 'test')
}
w461
  • 2,168
  • 4
  • 14
  • 40
  • 1
    Does this answer your question? [Dynamically setting variable name in Dart](https://stackoverflow.com/questions/23039314/dynamically-setting-variable-name-in-dart) – Nikolai Henriksen Dec 04 '20 at 16:45
  • not really, the other question is about dynamically creating variables, mine about modifying – w461 Dec 04 '20 at 18:36

2 Answers2

1

To do this you need to use MAP object

  List<Map<String, dynamic>> tasks;

  Future<void> changeTaskValue(int taskId, String variable, dynamic newValue) {
    tasks[taskId][variable] = newValue;
  }
towhid
  • 2,778
  • 5
  • 18
  • 28
  • Then I would have a different data structure. I was keen about a general method how to update nested classes within the repository from a bloc. – w461 Dec 04 '20 at 18:40
  • What you are looking for, isn't possible in Dart, you can check out this ans https://stackoverflow.com/questions/53737110/get-variables-name-by-its-value-in-dart-lang – towhid Dec 05 '20 at 05:02
1

One thing is you can't modify final variables. So what you can do is delete the Task object form the list and add another Task with the data you wanted.

List<Task> tasks;

Future<void> changeTaskValue({
  int taskId,
  String taskname,
  String status,
}) {
  tasks.remove(
    Task(taskId: 1), //id of the task you want to remove
  );
  tasks.add(Task(
    taskId: taskId,
    taskName: taskname,
    status: status,
  ));
}

class Task {
  Task({
    this.taskId,
    this.taskName,
    this.status,
  });
  final int taskId;
  final String taskName;
  final String status;
}

void abc() {
  changeTaskValue(taskId: 1, taskname: 'taskName', status: 'test');
}
biniyam112
  • 956
  • 1
  • 11
  • 17
  • good point, with final. I just copied some similar, handy class to write the example. Yes, It think your idea about providing the whole, updated task element is probably the easiest workaround – w461 Dec 04 '20 at 18:38