Flutter - the argument type 'void Function()' can't be assigned to the parameter type 'void Function(bool?)?'

Viewed 1981

: Error: The argument type 'void Function(dynamic)' can't be assigned to the parameter type 'void Function()'. lib/widgets/tasks_list.dart:25 checkboxCallback: (checkboxState) {

                        ^

: Error: The argument type 'void Function()' can't be assigned to the parameter type 'void Function(bool?)?'. lib/widgets/task_tile.dart:25 onChanged: checkboxCallback,

class TasksList extends StatefulWidget {
  @override
  State<TasksList> createState() => _TasksListState();
}

class _TasksListState extends State<TasksList> {
  List<Task> tasks = [
    Task(name: 'Buy milk'),
    Task(name: 'Buy eggs'),
    Task(name: 'Buy bread'),
  ];
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return TaskTile(
          taskTitle: tasks[index].name,
          isChecked: tasks[index].isDone,
          checkboxCallback: (checkboxState) {
            setState(() {
              tasks[index].toggleDone();
            });
          },
        );
      },
      itemCount: tasks.length,
    );
  }
} 
class TaskTile extends StatelessWidget {
  final bool? isChecked;
  final String? taskTitle;
  final VoidCallback checkboxCallback;

  TaskTile({
    this.isChecked,
    this.taskTitle,
    required this.checkboxCallback,
  });

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      title: Text(
        taskTitle!,
        style: TextStyle(
          decoration: isChecked! ? TextDecoration.lineThrough : null,
        ),
      ),
      activeColor: Colors.lightBlueAccent,
      value: isChecked,
      onChanged: checkboxCallback,
    );
  }
}
1 Answers

VoidCallback is useful for callback events with no expected value. For scenarios where you want to return a value back to the parent, you will want to use Function(x).

ie,

You should update your TaskTile widget like mentioned below

class TaskTile extends StatelessWidget {
final bool? isChecked;
final String? taskTitle;

// You should specify the parameter type that you want to pass.
final Function(bool?) checkboxCallback;

TaskTile({
  this.isChecked,
  this.taskTitle,
  required this.checkboxCallback,
 });

@override
Widget build(BuildContext context) {
  return CheckboxListTile(
    title: Text(
    taskTitle!,
    style: TextStyle(
      decoration: isChecked! ? TextDecoration.lineThrough : null,
    ),
  ),
  activeColor: Colors.lightBlueAccent,
  value: isChecked,
  onChanged: checkboxCallback,
   );
 }
}
Related