Search code examples
flutteruser-interfaceuser-input

Having a row of buttons for selecting moods in flutter


I want to make a row of buttons sort of like the ones in this picture

sort of like this

except i want the icons to be numbers and the selected button to be a different color to the rest of the items

I can't really find anything that has what I need as i also need to have one of the selectors to only show up when a true or false button above has also been selected. and I also need to return whether or not the true or false has been selected.

if anyone has any ideas or advice on how I would go about doing this, I would seriously just appreciate it so so much. thank you so much in advance


Solution

  • Please review the code below, which I hope will be helpful to you.

    int _selectedIndex = -1; // Initially no button is selected
    
    
     Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(5, (index) {
                    return IconButton(
                      icon: _buildIcon(index),
                      onPressed: () {
                        setState(() {
                          _selectedIndex = index;
                        });
                      },
                      color: _selectedIndex == index ? Colors.green : null,
                    );
                  }),
                ),
    

    Define different icons based on rating level

      Icon _buildIcon(int index) {
        switch (index) {
          case 0:
            return Icon(Icons.sentiment_very_dissatisfied); // Lowest rating
          case 1:
            return Icon(Icons.sentiment_dissatisfied); // Moderate-low rating
          case 2:
            return Icon(Icons.sentiment_neutral); // Neutral rating
          case 3:
            return Icon(Icons.sentiment_satisfied); // Moderate-high rating
          case 4:
            return Icon(Icons.sentiment_very_satisfied); // Highest rating
          default:
            return Icon(Icons.star_border); // Default icon
        }
      }
    

    Output:

    enter image description here