-1

Guys I am trying to access a variable inside a method and I had to pass this variable to reference method. is that possible?

This is my list builder

return ListView.builder(
      itemCount: tasks.length,
      itemBuilder: (context, index) {
        return TaskTile(
          nameOfTheTask: tasks[index].nameOfTheTask,
          isChecked: tasks[index].taskStatus,
          onTaskCompleted: (checkBoxState) {        
            setState(() {
              tasks[index].updateTaskStatus();
            });
          }, 
        );
      },
    );

I want to replace the callback near onTaskCompleted to a reference method.

onTaskChangedReference(checkBoxState) {
     setState(() {
       tasks[index].taskStatus =
           !tasks[indexOfTheTaskTile].taskStatus;
     });
   }

but I need to use the index variable, is there any way I can do that.

1 Answers1

1

One way to go about doing that is to create a method like this:

onTaskChangedReference(int index) {
  return (checkBoxState) {
     setState(() {
       tasks[index].taskStatus =
           !tasks[indexOfTheTaskTile].taskStatus;
     });
   }
}

So now in your ListView.builder, you can reference it like this:

...
onTaskCompleted: onTaskChangedReference(index),
...
Efthymis
  • 1,326
  • 11
  • 13
  • I did as you said and then I got the error setState() or markNeedBuild() called during build. error – Umakanth Pendyala Jul 07 '20 at 03:50
  • It might have something to do with the `TaskTile` implementation, check if you have something like this in your code: https://stackoverflow.com/a/47592505/1006555 – Efthymis Jul 07 '20 at 04:16