Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Checkbox in Flutter with 3 values

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.

like image 874
iDecode Avatar asked Jan 30 '26 06:01

iDecode


1 Answers

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),
)
like image 182
iDecode Avatar answered Feb 02 '26 02:02

iDecode