flutter 参数类型“Function”不能分配给参数类型“void Function(bool?)?'. null对象

0ejtzxu1  于 2023-05-01  发布在  Flutter
关注(0)|答案(4)|浏览(198)

这里是我的代码**,错误是在fluttre更新为2之后。第13章请帮帮忙...error is on TaskCheckBox class onchanged methodand dart analys return The argument type 'Function' can't be assigned to the parameter type 'void Function(bool?)?'.**

class TaskTile extends StatefulWidget {
  @override
  _TaskTileState createState() => _TaskTileState();
}

class _TaskTileState extends State<TaskTile> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        'This is task.',
        style: TextStyle(
          decoration: isChecked ? TextDecoration.lineThrough : null,
        ),
      ),
      trailing: TaskCheckBox(checkboxState: isChecked,toggleCheckboxState: (bool checkboxState) {
        setState(() {
          isChecked = checkboxState;
        });
      }),
    );
  }
}

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

  TaskCheckBox({required this.checkboxState,required this.toggleCheckboxState});

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

ccgok5k51#

您发送的是一个期望接收布尔值的函数,但在TaskCheckBox中,您接收的是一个普通函数。CheckBox也期望接收相同的类型,一个具有bool值的函数
换成这个

final Function(bool) toggleCheckboxState;

最终结果

class TaskCheckBox extends StatelessWidget {
  final bool checkboxState;
  final Function(bool) toggleCheckboxState;

  TaskCheckBox({
    @required this.checkboxState,
    @required this.toggleCheckboxState,
  });
jv4diomz

jv4diomz2#

我在另一篇文章error: The argument type 'void Function(bool)' can't be assigned to the parameter type 'void Function(bool?)'上回答了这个问题
我更新了checkboxCallback方法:

void checkBoxCallBack(bool? checkBoxState) {
    if (checkBoxState != null) {
      setState(() {
        isChecked = checkBoxState;
      });
    }
  }

CheckboxonChanged:属性转换为:

onChanged: toggleCheckboxState as void Function(bool?)?,

它消除了错误。

wmomyfyw

wmomyfyw3#

我得到了同样的错误,然后我把theowl-0011的答案与p2 kr结合起来解决了这个问题。它的工作...
toggleCheckBox:改为:

(bool? checkBoxState) {
    if (checkBoxState != null) {
      setState(() {
        isChecked = checkBoxState;
      });
    }

final Function toggleCheckbox;为:

final Function(bool?) toggleCheckbox;
b0zn9rqh

b0zn9rqh4#

无法将参数类型“Function”分配给参数类型“void Function(bool?)?'.
我换了台词
final函数toggle复选框;致:
final函数(bool?);
修好了

相关问题