fluttersetstateonpressiconbutton

Flutter IconButton not setting state onPress


I am trying to get my IconButton to return a setState with a text value which we then render out further in the widget tree but it appears that the setState isn't being applied

IconButton _buildRating(message, color, icon) {
    return IconButton(
      enableFeedback: true,
      iconSize: MediaQuery.of(context).size.width * .2,
      onPressed: () {
        switch (message) {
          case 'Very Dissatisfied':
            rating = 1;
            ratingDesc = 'Terrible';
            break;
          case 'Dissatisfied':
            rating = 2;
            ratingDesc = 'Bad';
            break;
          case 'Neutral':
            rating = 3;
            ratingDesc = 'Ok, but had some issues';
            break;
          case 'Satisfied':
            rating = 4;
            ratingDesc = 'Good, not great';
            break;
          case 'Very Satisfied':
            rating = 5;
            ratingDesc = 'Everything was great!';
            break;
        }
      },
      tooltip: message,
      icon: Icon(icon, color: color),
    );
  }
Text _buildRatingDesc() {
    return Text(ratingDesc, style: Theme.of(context).textTheme.bodyText2);
  }
SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        _buildRating('Very Dissatisfied', Colors.red,
                            Icons.sentiment_very_dissatisfied),
                        _buildRating('Dissatisfied', Colors.amber,
                            Icons.sentiment_dissatisfied),
                        _buildRating(
                            'Neutral', Colors.blue, Icons.sentiment_neutral),
                        _buildRating('Satisfied', Colors.lightGreen,
                            Icons.sentiment_satisfied),
                        _buildRating('Very Ssatisfied', Colors.green,
                            Icons.sentiment_very_satisfied),
                      ],
                    )),
                _buildRatingDesc(),

Solution

  • Wrap your function in setState(() {})

    onPressed: () {
        setState(() {
        switch (message) {
          case 'Very Dissatisfied':
            rating = 1;
            ratingDesc = 'Terrible';
            break;
          case 'Dissatisfied':
            rating = 2;
            ratingDesc = 'Bad';
            break;
          case 'Neutral':
            rating = 3;
            ratingDesc = 'Ok, but had some issues';
            break;
          case 'Satisfied':
            rating = 4;
            ratingDesc = 'Good, not great';
            break;
          case 'Very Satisfied':
            rating = 5;
            ratingDesc = 'Everything was great!';
            break;
        }})
      },