颤振中的自定义复选框代表3个值

问题描述 投票:0回答:1

Dart中的bool可以具有以下任何一个值

  • null
  • true
  • false

我想要一个像这样的Checkbox

enter image description here

[第一次,我有boolnull,所以请向我显示一个空框,然后我的值将是truefalse,所以请给我显示相应的小部件。

flutter dart flutter-layout
1个回答
0
投票

创建此小部件(可从外部定制):

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;
  CheckStatus _status;

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void didUpdateWidget(MyCheckbox oldWidget) {
    super.didUpdateWidget(oldWidget);
    _init();
  }

  void _init() {
    _checked = widget.value;

    if (_checked == null) {
      _status = CheckStatus.empty;
    } else if (_checked) {
      _status = CheckStatus.checked;
    } else {
      _status = CheckStatus.unchecked;
    }
  }

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

    switch (_status) {
      case CheckStatus.empty:
        break;
      case CheckStatus.checked:
        fillColor = widget.checkedFillColor;
        iconColor = widget.checkedIconColor;
        iconData = widget.checkedIcon;
        break;
      case CheckStatus.unchecked:
        fillColor = widget.uncheckedFillColor;
        iconColor = widget.uncheckedIconColor;
        iconData = widget.uncheckedIcon;
        break;
    }

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

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

enum CheckStatus {
  empty,
  checked,
  unchecked,
}

并像这样使用它:

bool _value;

MyCheckbox(
  value: _value,
  onChanged: (value) => setState(() => _value = value),
)
© www.soinside.com 2019 - 2024. All rights reserved.