How to make Flutter RaisedButton selected state

Viewed 13746

How to make RaisedButton as selected state as in toggle button selected state?

How to make RaisedButton not taking extra width, i.e, shrimpWrap the label text.

enter image description here

2 Answers

In order to reproduce a "2 state button" I personny use AnimatedCrossFade to switch between a RaisedButton and a OutlineButton. This way the state is handled directly in the crossFadeState property of AnimatedCrossFade widget.

Here is a widget you can use anywhere you want. The width is set to avoid bad clipping effect. It has to be sufficent to display the full text. As it's a stateless widget it's the responsability of the user of this widget to change the state.

class ToggleButton extends StatelessWidget {
  final selected, onChange, textSelected, textUnselected, width;

  ToggleButton({this.textSelected, this.textUnselected, this.selected, this.onChange, this.width = 150}) {}

  @override
  Widget build(BuildContext context) {
    return AnimatedCrossFade(
      duration: Duration(milliseconds: 200),
      crossFadeState: selected ? CrossFadeState.showFirst : CrossFadeState.showSecond,
      firstChild: Container(
        width: width,
        child: RaisedButton(
          child: Text(textSelected),
          onPressed: () {
            onChange(false);
          },
        ),
      ),
      secondChild: Container(
        width: width,
        child: OutlineButton(
          child: Text(textUnselected),
          onPressed: () {
            onChange(true);
          },
        ),
      ),
    );
  }
}

And you can use this widget as simply as :

ToggleButton(
  textSelected: "Account enabled",
  textUnselected: "Account disabled",
  width: 150,
  selected: _accountEnabled,
  onChange: (value) {
    setState(() {
      _accountEnabled = value;
    });
  },
)
Related