简体   繁体   English

Flutter:通过类构造函数传递函数参数

[英]Flutter: pass a fuction parameter through class constructor

I have 2 classes TasksTile and TaskCheckbox .我有 2 个类TasksTileTaskCheckbox So I need to pass 2 parameters form TasksTile to TaskCheckbox .所以我需要将 2 个参数从TasksTileTaskCheckbox So I created a constructor on TaskCheckbox with 2 parameters所以我在TaskCheckbox上创建了一个带有 2 个参数的构造函数

I want to pass those parameters from TasksTile as我想将这些参数从TasksTile

// 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?)?'.我在onChanged: toggleCheckboxstate,收到错误onChanged: toggleCheckboxstate,说:无法将参数类型“Function”分配给参数类型“void Function(bool?)?”。 I think the problem is in here final Function toggleCheckboxstate;我认为问题出在这里final Function toggleCheckboxstate; it is works fine in older flutter but not in the latest version.它在较旧的颤振中工作正常,但在最新版本中无效。

Try:尝试:

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

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;
    });
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM