Home > Blockchain >  Flutter: pass a fuction parameter through class constructor
Flutter: pass a fuction parameter through class constructor

Time:11-06

I have 2 classes TasksTile and TaskCheckbox. So I need to pass 2 parameters form TasksTile to TaskCheckbox. So I created a constructor on TaskCheckbox with 2 parameters

I want to pass those parameters from TasksTile as

// TasksTile class
return ListTile(
      title: Text(
        'data',
        style: TextStyle(
          decoration: isChecked ? TextDecoration.lineThrough : null,
        ),
      ),
      trailing: TaskCheckbox(isChecked, checkboxCallBack), // passing those
    );

my fuunction :

// TasksTile class
  void checkboxCallBack(bool checkboxState) {
    setState(() {
      isChecked = checkboxState;
    });
  }

my constructor:

//TaskCheckbox class
TaskCheckbox(this.checkboxState, this.toggleCheckboxstate); // this is my constructor
    final bool checkboxState; 
    final  Function toggleCheckboxstate;

then I just assigned the parameters to the code as

//TaskCheckbox class
@override
  Widget build(BuildContext context) {
    return Checkbox(
      activeColor: Colors.lightBlueAccent,
      value: checkboxState, // this is the fisrt one and it is bool so it works fine.
      onChanged: toggleCheckboxstate, // this is the seconde one it is a Fucntion and here is the problem 
    );
  }

I got an error here onChanged: toggleCheckboxstate, said : The argument type 'Function' can't be assigned to the parameter type 'void Function(bool?)?'. I think the problem is in here final Function toggleCheckboxstate; it is works fine in older flutter but not in the latest version.

CodePudding user response:

Try:

trailing: TaskCheckbox(checkboxState: isChecked, toggleCheckboxstate: (bool checkboxState) {
 setState(() {
      isChecked = checkboxState;
    });
});

CodePudding user response:

In my case here is the solution:

  TaskCheckbox({this.checkboxState, this.toggleCheckboxstate});
  final bool? checkboxState;
  final void Function(bool?)? toggleCheckboxstate; // here what had been chenged

and then changed the function also

  void checkboxCallBack(checkboxState) { //Removed bool from (bool checkboxState)
    setState(() {
      isChecked = checkboxState;
    });
   }
  • Related