Multiple Checkbox in Flutter with 3 values

1,155

Create this widget (customizable from outside):

class MyCheckbox extends StatefulWidget {
  final bool? value;
  final ValueChanged<bool?> onChanged;
  final Color? checkedIconColor;
  final Color? checkedFillColor;
  final IconData? checkedIcon;
  final Color? uncheckedIconColor;
  final Color? uncheckedFillColor;
  final IconData? uncheckedIcon;

  const MyCheckbox({
    Key? key,
    required this.value,
    required this.onChanged,
    this.checkedIconColor = Colors.white,
    this.checkedFillColor = Colors.teal,
    this.checkedIcon = Icons.check,
    this.uncheckedIconColor = Colors.white,
    this.uncheckedFillColor = Colors.red,
    this.uncheckedIcon = Icons.close,
  }) : super(key: key);

  @override
  _MyCheckboxState createState() => _MyCheckboxState();
}

class _MyCheckboxState extends State<MyCheckbox> {
  bool? _checked;

  @override
  void initState() {
    super.initState();
    _checked = widget.value;
  }

  @override
  void didUpdateWidget(MyCheckbox oldWidget) {
    super.didUpdateWidget(oldWidget);
    _checked = widget.value;
  }

  Widget _buildIcon() {
    Color? fillColor;
    Color? iconColor;
    IconData? iconData;

    var checked = _checked;
    if (checked != null) {
      if (checked) {
        fillColor = widget.checkedFillColor;
        iconColor = widget.checkedIconColor;
        iconData = widget.checkedIcon;
      } else {
        fillColor = widget.uncheckedFillColor;
        iconColor = widget.uncheckedIconColor;
        iconData = widget.uncheckedIcon;
      }
    }

    return Container(
      decoration: BoxDecoration(
        color: fillColor,
        border: Border.all(color: Colors.grey),
      ),
      child: Icon(
        iconData,
        color: iconColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: _buildIcon(),
      onPressed: () {
        bool? result = _checked;
        widget.onChanged(result == null ? true : result ? false : null);
      },
    );
  }
}

And use it like:

bool? _value;

MyCheckbox(
  value: _value,
  onChanged: (value) => setState(() => _value = value),
)
Share:
1,155
iDecode
Author by

iDecode

When developers want to hide something from you, they put it in docs.

Updated on December 20, 2022

Comments

  • iDecode
    iDecode over 1 year

    A bool in Dart can have any of these values

    • null
    • true
    • false

    I want to have a Checkbox which works like this:

    enter image description here

    The very first time, I have bool value null, so show me empty box, after that my value would be either true or false, so show me corresponding widget.