Flutter - How do I toggle the color of a RaisedButton upon click? Flutter - How do I toggle the color of a RaisedButton upon click? flutter flutter

Flutter - How do I toggle the color of a RaisedButton upon click?


This button will need to be created in the build of a State of a StatefulWidget, and the State must have a member variable bool pressAttention = false;. As Edman suggests, you need to make state changes in a setState callback for the Widget to redraw.

new RaisedButton(  child: new Text('Attention'),  textColor: Colors.white,  shape: new RoundedRectangleBorder(    borderRadius: new BorderRadius.circular(30.0),  ),  color: pressAttention ? Colors.grey : Colors.blue,  onPressed: () => setState(() => pressAttention = !pressAttention),);


If you want the button to change color for the pressed state you just need to use the "highlightColor" property in RaisedButton

       RaisedButton(          onPressed: () {},          child: Text("Test"),          highlightColor: YOUR_PRESSED_COLOR, //Replace with actual colors          color: IDLE_STATE_COLOR,        ),


Or you can use rxdart:

import 'package:rxdart/rxdart.dart';...bool presssedFavorite = false;final _pressAttention = BehaviorSubject<bool>();Observable<bool> get coursesStream => _pressAttention.stream;...StreamBuilder(stream: _pressAttention,builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {if (snapshot.hasData)  presssedFavorite = snapshot.data;  return RawMaterialButton(      onPressed: (){        _addToFavorites(context);      },      child: Padding(        padding: EdgeInsets.all(5),        child: Icon(          presssedFavorite ? Icons.favorite : Icons.favorite_border,          color: Colors.red,          size: 17,        ),      ),    );  },),void _addToFavorites(BuildContext context) async{  //my code...  _pressAttention.sink.add(!presssedFavorite);}

It is more complicated, but you can use this solution also with web services, firestore, db... And you can use with StatelessWidget and StatefulWidget.