在Flutter中,如何将void函数作为参数从有状态小部件传递到无状态的子小部件?

pn9klfpd  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(145)

构建简单的待办事项应用程序。问题出在两个小部件上:TaskTile和TaskCheckbox。TaskTile应该向下传递一个布尔值和一个函数,以将此布尔值更改为其子TaskCheckbox,这反过来又会触发void函数并实际更改其值。

任务磁贴:

import 'package:flutter/material.dart';
import 'task_checkbox.dart';

class TaskTile extends StatefulWidget {
  const TaskTile({
    super.key,
    required this.taskName,
  });

  final String taskName;

  @override
  State<TaskTile> createState() => _TaskTileState();
}

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

  void checkboxCallback({required bool checkboxState}) {
    setState(() {
      isChecked = !checkboxState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          widget.taskName,
          style: TextStyle(
            color: Colors.white,
            decoration: isChecked ? TextDecoration.lineThrough : null,
          ),
        ),
        TaskCheckbox(
          checkboxState: isChecked,
          toggleCheckboxState: checkboxCallback(checkboxState: isChecked),
        ),
      ],
    );
  }
}

任务复选框:

import 'package:flutter/material.dart';

class TaskCheckbox extends StatelessWidget {
  const TaskCheckbox({
    super.key,
    required this.checkboxState,
    required this.toggleCheckboxState,
  });

  final bool checkboxState;
  final void toggleCheckboxState;

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      value: checkboxState,
      onChanged: (value) {
        toggleCheckboxState;
      },
      checkColor: Colors.black,
      activeColor: const Color(0xff7df9ff),
      side: const BorderSide(
        color: Colors.white70,
      ),
    );
  }
}

使用上面的代码,我不断得到这个错误:

lib/widgets/task_tile.dart:39:32: Error: This expression has type 'void' and can't be used.
          toggleCheckboxState: checkboxCallback(checkboxState: isChecked),
bz4sfanl

bz4sfanl1#

首先,在TaskCheckbox中,将toggleCheckboxState的声明更改为:

final void Function(bool) toggleCheckboxState;

然后在其build()小部件中,按如下方式设置onChanged:

// ...
onChanged: toggleCheckboxState,

然后当你试图从TaskTile小部件调用它时,这样调用它:

// ...
  toggleCheckboxState: (value) {
    checkboxCallback(checkboxState: value);
  },

相关问题