Reputation: 28886
A bool
in Dart can have any of these values
I want to have a Checkbox
which works like this:
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.
Upvotes: 3
Views: 1696
Reputation: 28886
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),
)
Upvotes: 5