Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to make a reusable button change its image and color?

Tags:

flutter

dart

I have a button that I can use on multiple different pages. I want to be able to change the image and fill the OutlineButton with a color when it's pressed. How can this be accomplished?

class BackArrowButton extends StatelessWidget {
  final Widget child;
  final GestureTapCallback onPressed;
  BackArrowButton({@required this.onPressed, this.child});

  @override
  Widget build(BuildContext context) {
    return OutlineButton(
      padding: const EdgeInsets.all(15.0),
      child: child,
      borderSide: BorderSide(width: 1.0, color: Color(0xff1A1A1A)),
      highlightElevation: 0.0,
      highlightedBorderColor: Color(0xFF1A1A1A),
      splashColor: Color(0x1F1A1A1A),
      shape: CircleBorder(),
      onPressed: onPressed,
    );
  }

This is what I call on multiple pages to show the button.

BackArrowButton(
  child: ClipOval(
    child: Container(
      child: Image.asset(
        'assets/images/icons/arrow_back.png',
      ),
    ),
  ),
  onPressed: () {
    Navigator.pop(context, '/home');
  },
),
like image 626
Chris Avatar asked Oct 22 '25 14:10

Chris


1 Answers

Make your button a statefullWidget and add setState to the onPress call.

class BackArrowButton extends StatefulWidget {
  final Widget child;
  final GestureTapCallback onPressed;

  BackArrowButton({@required this.onPressed, this.child});

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


class _BackArrowButtonState extends State<BackArrowButton> {



  @override
  void initState() {
    _color = Colors.green;
    super.initState();
  }

  Color _color;
  @override
  Widget build(BuildContext context) {
    return OutlineButton(
      padding: const EdgeInsets.all(15.0),
      child: widget.child,
      borderSide: BorderSide(width: 1.0, color: Color(0xff1A1A1A)),
      highlightElevation: 0.0,
      highlightedBorderColor: _color,
      splashColor: Color(0x1F1A1A1A),
      shape: CircleBorder(),
      onPressed: (){
        setState((){
           _color = Colors.red;
        });
        widget.onPressed();
      },
    );
  }
}
like image 133
Glen Avatar answered Oct 25 '25 04:10

Glen