es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

El tipo de argumento ‘Function’ no puede ser asignado al tipo de parámetro ‘void Function(bool?)’.

Mientras estaba creando una aplicación, ocurrió un error que dice: El tipo de argumento ‘Function’ no se puede asignar al tipo de parámetro ‘void Function(bool?)?’. dentro del widget sin estado Taskcheckbox en onChanged: toggleCheckState dice que la función toggleCheckboxState no se puede asignar.

“`
class task_tile extends StatefulWidget {
@override
State<task_tile> createState() => _task_tileState();
}

class _task_tileState extends State<task_tile> {
bool ischanged = false;

@override
Widget build(BuildContext context) {
return ListTile(
title: Text("This is a box", style: TextStyle(
decoration: ischanged ? TextDecoration.lineThrough : null
),
),
trailing: Taskcheckbox(ischanged, (bool checkboxState) {
setState(() {
ischanged = checkboxState;
});
}),
);
}
}

class Taskcheckbox extends StatelessWidget {
final bool checkboxState;
final Function toggleCheckboxState;

Taskcheckbox(this.checkboxState, this.toggleCheckboxState);

@override
Widget build(BuildContext context) {
return Checkbox(
activeColor: Colors.lightBlueAccent,
value: checkboxState,
onChanged: toggleCheckboxState,
);
}
}
“`

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    El mensaje de error El tipo de argumento 'Function' no se puede asignar al tipo de parámetro 'void Function(bool?)?' sugiere que hay una incompatibilidad entre el tipo de parámetro esperado y el tipo real de la función toggleCheckboxState.

    En el fragmento de código, el widget Taskcheckbox recibe como argumentos un valor booleano checkboxState y una función toggleCheckboxState. La propiedad onChanged del widget Checkbox dentro del widget Taskcheckbox se establece en toggleCheckboxState. Sin embargo, la función toggleCheckboxState que se pasa como argumento a Taskcheckbox tiene la firma incorrecta. La propiedad onChanged espera una función que tome un solo argumento booleano y devuelva void, es decir, void Function(bool?)?.

    Para solucionar el error, asegúrate de que la función toggleCheckboxState tenga la firma correcta. Debe tomar un solo argumento booleano y devolver void. Aquí tienes una versión actualizada del código con la firma corregida:

    class Taskcheckbox extends StatelessWidget {
      final bool checkboxState;
      final void Function(bool?) toggleCheckboxState;
    
      Taskcheckbox(this.checkboxState, this.toggleCheckboxState);
    
      @override
      Widget build(BuildContext context) {
        return Checkbox(
          activeColor: Colors.lightBlueAccent,
          value: checkboxState,
          onChanged: toggleCheckboxState,
        );
      }
    }
    

    Con este cambio, el código debería compilar sin errores.

Comments are closed.