首页 > 解决方案 > 如何在颤动中自定义单选按钮?

问题描述

我想做这些按钮,我尝试使用单选按钮,但我无法自定义它们。你有什么想法我该怎么做?

按钮

标签: flutter

解决方案


我写了一个模仿单选按钮行为的可重复使用的小部件:

自定义收音机小部件

class CustomRadioWidget<T> extends StatelessWidget {
  final T value;
  final T groupValue;
  final ValueChanged<T> onChanged;
  final double width;
  final double height;

  CustomRadioWidget({this.value, this.groupValue, this.onChanged, this.width = 32, this.height = 32});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: GestureDetector(
        onTap: () {
          onChanged(this.value);
        },
        child: Container(
          height: this.height,
          width: this.width,
          decoration: ShapeDecoration(
            shape: CircleBorder(),
            gradient: LinearGradient(
              colors: [
                Color(0xFF49EF3E),
                Color(0xFF06D89A),
              ],
            ),
          ),

          child: Center(
            child: Container(
              height: this.height - 8,
              width: this.width - 8,
              decoration: ShapeDecoration(
                shape: CircleBorder(),
                gradient: LinearGradient(
                  colors: value == groupValue ? [
                    Color(0xFFE13684),
                    Color(0xFFFF6EEC),
                  ] : [
                    Theme.of(context).scaffoldBackgroundColor,
                    Theme.of(context).scaffoldBackgroundColor,
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

您可以将其添加到您的代码中,例如:

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
     CustomRadioWidget(
           value: "0",
           groupValue: _radValue,
           onChanged: (String value) {
              setState(() {
                 _radValue = value;
              });
           },
      ),
      CustomRadioWidget(
           value: "1",
           groupValue: _radValue,
           onChanged: (String value) {
              setState(() {
                _radValue = value;
              });
           },
      ),
   ],
),

输出如下所示:

输出


推荐阅读