Flutter 开关按钮封装

文章目录

Flutter 开关按钮封装

效果

《Flutter 开关按钮封装》

实现思路

利用自定义按钮组件FlatButton,设置开关状态对应的颜色。

实现代码

///
/// Author: chengzan
/// Date: 2020-6-4
/// Describe: 圆形按钮,适用开关按钮
///

class PowerSwitch extends StatefulWidget { 
  var value;
  var on;
  var off;
  Color mainThemeColor;
  String onText;
  String offText;
  Function changed;
  PowerSwitch(
      { Key key,
      @required this.value,
      @required this.on,
      @required this.off,
      @required this.mainThemeColor,
      @required this.onText,
      @required this.offText,
      @required this.changed});

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

class _PowerSwitchState extends State<PowerSwitch> { 
  var value;

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

  @override
  Widget build(BuildContext context) { 
    return FlatButton(
        color: value == widget.on ? widget.mainThemeColor : Color(0xffffffff),
        splashColor: widget.mainThemeColor,
        highlightColor: widget.mainThemeColor,
        child: Icon(
          Icons.power_settings_new,
          color: value == widget.on ? Color(0xffffffff) : widget.mainThemeColor,
        ),
        onPressed: () { 
          setState(() { 
            value = value == widget.on ? widget.off : widget.on;
          });
          widget.changed(value);
        },
        shape: new CircleBorder(
          side: new BorderSide(
            //设置 界面效果
            width: 1,
            color:
                value == widget.on ? widget.mainThemeColor : Color(0xffe7e7e7),
            style: BorderStyle.solid,
          ),
        ));
  }
}
    原文作者:CN-cheng
    原文地址: https://blog.csdn.net/github_37125043/article/details/109401810
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞