Waleed Alrashed
Waleed Alrashed

Reputation: 987

Draw Border around FlatButton when clicked

Goal: Drawing a border around the FlatButton whenever the user presses that button.

In other words: onPressed() is invoked ? -> DrawBorder()


Use Case: The final UI should allow the user to choose multiple Buttons, those chosen buttons should have a border to let the user know that they have been selected.

Problem: Can not draw the border programmatically, let alone having multiple buttons (About 9 buttons or so) in the same UI.

Screenshot showing the buttons

Button Code:

 FlatButton(
   color: kWhite,
   onPressed: () {},
   child: Image.asset('assets/images/gucci.jpg'),
   shape: RoundedRectangleBorder( //Draw when user clicks on the button 
     side: BorderSide(
     color: kDarkTitleColor, width: 1),
     ),
       padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
      ),

Upvotes: 3

Views: 1091

Answers (1)

RoduanKD
RoduanKD

Reputation: 1309

You can wrap your button in a StatefulWidget like this:

class BorderedFlatButton extends StatefulWidget {
  @override
  _BorderedFlatButtonState createState() => _BorderedFlatButtonState();
}

class _BorderedFlatButtonState extends State<BorderedFlatButton> {
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      color: kWhite,
      onPressed: () {
        print(isSelected);
        setState(() {
          isSelected = !isSelected;
        });
      },
      child: Image.asset('assets/images/gucci.jpg'),
      shape: RoundedRectangleBorder(
        side: BorderSide(
            color: isSelected ? kDarkTitleColor : Colors.transparent, width: 1),
      ),
      padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
    );
  }
}

PS: Here I added an state variable isSelected that indicated if the button is selected or not.

Upvotes: 2

Related Questions