如何禁用复选框颤动

How to disable checkbox flutter

我在 ListTile 中使用复选框,如下所示:

 ListTile(
  leading: Checkbox(
  value: _isChecked,
    onChanged: (v) {
      setState(() {
          _isChecked = !_isChecked;
      });
    },
  ),
  title: Text("is Bathroom"),
);

如何禁用复选框。我知道 Checkbox 小部件是无状态的。但是 material 子包中是否提供了可以执行此操作的任何其他 Widget。类似于 InputDecorator.

我对 DropdownButton 也有同样的疑问。我按如下方式使用它从下拉列表中选择表单中的项目。

             InputDecorator(
                decoration: InputDecoration(
                  labelText: "Type",
                  hintText: "Choose the type",
                ),
                isEmpty: _type == null,
                child: DropdownButton<int>(
                  value: _type,
                  isDense: true,
                  onChanged: (value) {
                    setState(() {
                      _type = value;
                    });
                  },
                  items: _buildDropdownItemList(),
                ),
              );

我尝试了 InputDecoration 中的 enable 参数,但这只是改变了装饰。用户仍然可以更改选择。

您可以在 statefuldwiget 中使用 setstate 更改复选框状态我将留下我在 youtube 中找到的示例。

Here您可以观看有关如何使用它的示例。

您还可以看到来自同一个人的示例,他有一个关于各个小部件的完整系列,例如 Dropdown..

希望对您有所帮助。

您可以将 null 传递给 onChanged 属性,这将禁用复选框。

Checkbox(value: false, onChanged: null)

这是可以解决您问题的示例代码。

    class TaskTile extends StatefulWidget {
      const TaskTile({Key? key, required this.index}) : super(key: key);
      final int index;

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

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

      @override
      Widget build(BuildContext context) {
        return ListTile(
          trailing: TaskCheckBox(
              checkBoxState: isChecked, toggleCheckBoxState:  (bool? newCheckBoxState) {
        setState(() {
          isChecked = newCheckBoxState ?? isChecked;
        });
      }),
          title: Text(
            'Task ${widget.index}',
            style: TextStyle(
              decoration:
                  isChecked ? TextDecoration.lineThrough : TextDecoration.none,
            ),
          ),
        );
      }
    }

    class TaskCheckBox extends StatelessWidget {
      final bool checkBoxState;
      final void Function(bool?)? toggleCheckBoxState;

      const TaskCheckBox(
          {Key? key,
          required this.checkBoxState,
          required this.toggleCheckBoxState})
          : super(key: key);
      @override
      Widget build(BuildContext context) {
        return Checkbox(
            fillColor: MaterialStateProperty.all<Color>(Colors.lightBlue),
            value: checkBoxState,
            onChanged: toggleCheckBoxState);
      }
    }